(function (window) {
    var currentVoiceAudio, rec, wave, recBlob, _voiceTimer = 0, voiceInit = true, _voiceRunning = false,
        _clockTimer = 0,
        bussinessHistoryKeys = [], _clockTimer
        , RateExtendType = {STAR: 'S', FOLD: 'F', CHECKBOX: 'O', INPUT: 'I', RADIO: 'R'};
    var init = function () {
        $ROBOT.init($config.robotEngineConfig);
        return {
            client: {
                clientId: $config.client.clientId,
                clientName: $config.client.clientName,
                clientFirstName: $config.client.clientName,
                iconUrl: ($config.client.iconUrl || 'jsp/standard/theme/' + $config.theme + '/img/client.jpg'),
                iconAlt: i18n.scripts.me
            },
            agent: {
                id: $config.toUserId,
                iconUrl: 'jsp/standard/theme/' + $config.theme + '/img/agent.jpg',
                iconUrls: {},
                iconAlt: i18n.scripts.lemei,
                name: null,
                isRobotAgent: false
            },
            robot: {
                iconUrl: 'jsp/standard/resource/img/robot.jpg',
                isRobot: $config.isRobot,
                robotFirst: $config.robotFirst,
                robotType: '',
                robotName: '',
                robotId: '',
                iconAlt: $config.queue.robotEngineConfig.name || i18n.scripts.lemei,
                name: i18n.robot.name
            },
            lm: {
                name: $config.queue.lmShowName,
                title: $config.queue.lmTitle,
                url: $config.queue.lmPage,
                hrefUrl: ($config.queue.lmPage).startWith('http') ? $config.queue.lmPage : location.origin + $config.webchatUrl + "/clientLeaveMessage.do" + '?queue=' + $config.queueId + '&clientid=' + $config.client.clientId + '&from=' + _from

            },
            RateType: {
                CLIENT_SEND: 0,
                AGENT_SEND: 1,
                SHUT_SEND: 2,
                INTERVAL_SEND: 3
            },
            /*
                * 跳转满意度
                */
            OpenRate: {
                BEFORE_CLOSE: 0, //0 结束之后转满意度
                AFTER_CLOSE: 1, //先转满意度 在满意度中结束
                NOT_SHOW_RATE: 2, //不转满意度直接结束
                times: 0,
                hasRating: false
            },
            /**
             * 关闭类型
             */
            CloseType: {
                CLIENT_CLOSE: 0,
                AGENT_CLOSE: 1,
                CLIENT_AFK_CLOSE: 2
            },

            CLIENTTYPE: {
                NORMAL: 0,
                VISITOR: 1,
                WECHAT: 2,
                THIRD_PART: 3
            },
            /**
             * 请求状态类型
             */
            RequestStatus: {
                WAITING: 0,
                ACCEPTED: 1,
                REFUSED: 2,
                TIMEOUT: 3,
                UPDATENUMINQUEUE: 8,
                BLOCKED: 9,
                ROBOTACEPT: 11,
                DIFFERENT_SESSION_TYPE: -35
            },
            //基础ajax请求地址
            ajaxURL: 'jsonHttpRemote.do',
            NoticeMessageType: {
                NORMAL: 0,
                TRACK_CHANGE: 1,
                PUSH_RATING: 2,
                AFK_ELAPSED_NOTIFY: 3, //发送超时提示
                AFK_ELAPSED_CLOSE_SESSION: 4, //超时的时候结束聊天
                TYPING: 5,
                REVOKE_MESSAGE: 6,
                INVITE_NOTICE: 10,
                TRANSFER_NOTICE: 11,
                TRANSFER_NOTICE_START: 14,
                TRANSFER_NOTICE_FAIL: 15,
                AGENT_CLOSE_NOTICE: 12,
                SUPPLY_INFORMATION: 99
            },
            formatNoticeType: {
                QUEUE: 0,
                WAITING: 1,
                OUTTIME: 2
            },
            rate: {
                rateSender: 6,
                maxAllowRateTimes: $config.queue.rateTimes,
                hasRateTimes: 0,
                client: {
                    allowRateTimes: $config.queue.rateClientTimes,
                    allowRateWhenEnd: $config.queue.rateClientForEnd,
                    rateOrEnd: $config.queue.rateOrEnd,
                    hasRate: false,
                    hasRateTimes: 0
                },
                agent: {
                    allowRateTimes: $config.queue.rateAgenttTimes,
                    allowRateWhenEnd: $config.queue.rateAgentForEnd,
                    hasRate: false,
                    hasRateTimes: 0
                },
                rateType: {
                    CLIENT_SEND: 0,
                    AGENT_SEND: 1,
                    SHUT_SEND: 2,
                    INTERVAL_SEND: 3,
                    CLIENT_CLOSE: 4,
                    OUT_TIME: 5,
                    DEFAULT: 6
                },
                openRate: {
                    BEFORE_CLOSE: 0, //0 结束之后转满意度
                    AFTER_CLOSE: 1, //先转满意度 在满意度中结束
                    NOT_SHOW_RATE: 2 //不转满意度直接结束
                }
            }
        };
    };
    String.prototype.replaceAll = function (s1, s2) {
        if (s1) {
            return this.replace(new RegExp(s1, "gm"), s2);
        }
    }
    Constants = init();

    function bindOnBeforLoad() {
        $F.log("run bind on before load");
        var userAgent = navigator.userAgent;
        if (userAgent.indexOf("DingTalk") == -1) {
            $(window).on('beforeunload', function () {
                $F.doAjaxCall(Constants.ajaxURL, {
                    requestType: "writeLog",
                    content: "run windows beforeunload"
                });
                return "";
            });
        }
        $(window).on('unload', function () {
            $F.doAjaxCall(Constants.ajaxURL, {
                requestType: "writeLog",
                content: "run windows unload"
            });
            if (_sessionActive)
                endSession(Constants.rate.rateType.CLIENT_CLOSE);
        })
    }

    function bindOffBeforLoad() {
        $F.log("run bind on before load");
        var userAgent = navigator.userAgent;
        if (userAgent.indexOf("DingTalk") == -1) {
            $(window).off('beforeunload');
        }
        $(window).off('unload')
    }

    UI = {
        initRate: function () {
            if (typeof order != 'undefined' && order == 'DESC') {
                if (ratings[ratings.length - 1]) {
                    var checkId = ratings[ratings.length - 1].ratingWeight;
                    $('.checked', "#judge_pj_rg").removeClass('checked');
                    $('.rate' + checkId, "#judge_pj_rg").addClass("checked", true);
                    showClickRate(ratings.length - 1);
                }
            } else {
                if (ratings[0]) {
                    var checkId = ratings[0].ratingWeight;
                    $('.checked', "#judge_pj_rg").removeClass('checked');
                    $('.rate' + checkId, "#judge_pj_rg").addClass("checked", true);
                    showClickRate(0);
                }
            }

        },
        robotOnlYChangeUI() {
            // _transfering = false;
            //机器人模式
            $F.formatAndShowNotice(i18n.page.RobotWelcomeTip, true);
            $("#headTitle").html(i18n.page.headTitle_robot);
            $("#time_robot").html(i18n.page.chatTime_robot);
            $('.ke-toolbar').hide();
            $("#chatTime").hide();
            //隐藏属性
            $("#waitingForAcceptInChatView").show();
            $("#chatTimeONRobot").show();
            UI.showChangeModule();
            $("#sen_div").show();
            $('.main').addClass('robot').removeClass('customer');
            //对右边栏进行界面切换， 机器人的时候如果是单独的一个样式需要切换的时候需要在jsp里显示和隐藏
            if (typeof RIGHTPAGE != 'undefined' && RIGHTPAGE.robot && RIGHTPAGE.robot instanceof Function) {
                RIGHTPAGE.robot();
            }
            UI.loadCloseButton($config.queue);
        },

        robot: function () {
            $ROBOT.transferingChange(false);
            this.robotOnlYChangeUI();
        },
        cuestomerService: function () {
            $("#time").html(i18n.page.chatTime);
            UI.loadHeadTitle($config.queue);
            $("#chatTimeONRobot").hide();
            $('.ke-toolbar').hide();
            $("#sen_div").show();
            //显示属性
            UI.loadWorkTime($config.queue);
            //接通坐席之后自动关闭机器人模式
            Constants.robot.isRobot = false;
            _sessionActive = true;
            $('.main').removeClass('robot').addClass('customer');
            UI.hideChangeModule();
            //对右边栏进行界面切换， 机器人的时候如果是单独的一个样式需要切换的时候需要在jsp里显示和隐藏
            if (typeof RIGHTPAGE != 'undefined' && RIGHTPAGE.customer && RIGHTPAGE.customer instanceof Function) {
                RIGHTPAGE.customer();
            }
        },
        doEnd: function () {
            $("#time").html("聊天结束");
            clearInterval(timer);
            clearTimeout(_clockTimer);
            $("#chatTime").hide();
            chatEditor.readonly();
            $("#sen_div").hide();
            $('.close').hide();
            $("#close_div").hide();
            $F.formatAndShowNotice(i18n.common.endChat, true);
            $(".head-btn-container .close").hide();
            UI.hideChangeModule();
        },
        chatTool: function () {
            $('.ke-toolbar').show();
            $('#close_div').show();
            UI.loadCloseButton($config.queue);
            clearTimeout(_clockTimer);
        },
        displayNoneForInQueueNotice: function () {
            clearTimeout(_clockTimer);
            $('.inqueue-notice').css('display', 'none');
            $('.inqueue-load').css('display', 'none');
        },
        ratePc: function () {
            $(".main-title").html(($config.queue.rateTitle || i18n.common.ratePageContent.mainTitle).replace('{0}', Constants.agent.name || Constants.robot.name).replace('{1}', Constants.agent.id || Constants.robot.id));
        },
        rateClientShut: function () {
            $('.nav-title').html(($config.queue.rateClientShutTips || i18n.common.ratePageContent.clientCloseChat).replace('{0}', Constants.agent.name || Constants.robot.name).replace('{1}', Constants.agent.id || Constants.robot.id));
        },
        rateAgentShut: function () {
            $('.nav-title').html(($config.queue.rateAgentShutTips || i18n.common.ratePageContent.AgentCloseChat).replace('{0}', Constants.agent.name || Constants.robot.name).replace('{1}', Constants.agent.id || Constants.robot.id));
        },
        rateOutTime: function () {
            $('.nav-title').html(($config.queue.rateOutTimeTips || i18n.common.ratePageContent.AFKCloseChat).replace('{0}', Constants.agent.name || Constants.robot.name).replace('{1}', Constants.agent.id || Constants.robot.id));
        },
        rateAgentSend: function () {
            $('.nav-title').html(($config.queue.rateAgentSend || i18n.common.ratePageContent.navTitle).replace('{0}', Constants.agent.name || Constants.robot.name).replace('{1}', Constants.agent.id || Constants.robot.id));
        },
        rateClientSend: function () {
            $('.nav-title').html(($config.queue.rateClientSend || i18n.common.ratePageContent.navTitle).replace('{0}', Constants.agent.name || Constants.robot.name).replace('{1}', Constants.agent.id || Constants.robot.id));
        },
        loadLogo: function (head) {
            if (head.headLogo) {
                var headLogo = head.headLogo;
                if (headLogo == -1) {
                    $("#logo").hide();
                } else {
                    if (typeof headLogo == 'object') {
                        if (_from && headLogo.hasOwnProperty(_from)) {
                            $("#logo").attr("src", headLogo[_from]);
                        }
                    } else {
                        $("#logo").attr("src", headLogo);
                    }
                }
            }
        },
        loadHeadTitle: function (head) {
            if (head.headTitle) {
                if (head.headTitle == '-1') {
                    $("#headTitle").parent().hide();
                } else {
                    $("#headTitle").text(head.headTitle);
                }
            } else {
                $("#headTitle").text(i18n.page.headTitle);
            }
        },
        loadWorkTime: function (head) {
            if (head.workTime) {
                if (head.workTime == '-1') {
                    $("#workTime").hide();
                } else {
                    $("#workTime b").text(head.workTime);
                }
            }
        },
        loadChangeCustomer: function (head) {
            if (head.changeCustomer) {
                $("#changeModule").html(head.changeCustomer);
            }
        },
        loadHeadLm: function (head) {
            if (head.headLm) {
                if (head.headLm == -1) {
                    $("#leaveMsg_div").hide();
                } else {
                    $("#leaveMsg_div").text(head.headLm);
                }
            }
        },
        loadCloseButton: function (head) {
            if (head.closeButton) {
                if (head.closeButton == '-1') {
                    $("#back_div").hide();
                } else if (head.closeButton == '-2') {
                    $("#back_div").removeClass("noimg");
                    $("#back_div").show();
                } else {
                    $("#back_div").text(head.closeButton);
                    $("#back_div").show();
                }
            } else {
                $("#back_div").show();
            }
        },
        loadQCScan: function (head) {
            if (head.QRCode) {
                if (head.QRCode == '-1') {
                    $('.barcode, .barcode i').hide();
                } else {
                    $('.barcode, .barcode i').show();
                }
            }
        },
        loadChatTime: function (head) {
            if (head.chatTime) {
                if (head.chatTime == '0') {
                    $('#chatTime').hide();
                } else {
                    $('#chatTime').show();
                }
            }
        },
        showChangeModule: function () {
            $F.log("显示转人工操作");
            var head = $config.queue;
            if (head && head.changeCustomer && head.changeCustomer != "") {
                $("#changeModule").show();
                $(".manual").show();
            }
        },
        hideChangeModule: function () {
            $F.log("隐藏转人工操作");
            $('#changeModule, .manual').hide();
        },
        loadHotTop: function () {
            $F.doAjaxCall(Constants.ajaxURL, {
                requestType: "hotTop",
                sessionId: $config.sessionId
            }, function (data) {
                if (data.status == 'success') {
                    $F.log("hot top" + JSON.stringify(data));
                    if (data.hotTop) {
                        var r
                        var hotTop = data.hotTop;
                        if (hotTop) {
                            if (typeof hotTop != 'object') {
                                hotTop = JSON.parse(hotTop);
                            }
                            var rec = $config.queue.robotEngineConfig;
                            if (rec.type == 8) {
                                var errorCode = hotTop.errorCode;
                                if (errorCode == 0) {
                                    var result = hotTop.result;
                                    var resultArray = result.resultArray;
                                    var htmlQuest = "";
                                    $.each(resultArray, function (i, resultArr) {
                                        var hotQuestions = resultArr.hotQuestions;
                                        $.each(hotQuestions, function (i, hotQuestion) {
                                            htmlQuest += '<li>' +
                                                '<span class="title hot-question" data-content="' + hotQuestion + '">' + hotQuestion + '</span>' +
                                                '</li>';
                                        })
                                    })

                                    if (htmlQuest.length > 0) {
                                        $(".list1").html(htmlQuest);
                                    }
                                    $(".hot-question").off().on("click", function () {
                                        sendComment($(this).data("content"));
                                    })
                                }
                            } else if (rec.type == 9) {
                                if (hotTop.isSuccess == 1) {
                                    var result = hotTop.result;
                                    var htmlQuest = "";
                                    if (result.length > 0) {
                                        $.each(result, function (i, hotQuestion) {
                                            htmlQuest += '<li>' +
                                                '<span class="title hot-question" data-content="' + hotQuestion.question + '">' + hotQuestion.question + '</span>' +
                                                '</li>';
                                        })
                                    }
                                    if (htmlQuest.length > 0) {
                                        $(".list1").html(htmlQuest);
                                    }
                                    $(".hot-question").off().on("click", function () {
                                        sendComment($(this).data("content"));
                                    })
                                }
                            } else {
                                var code = hotTop.code;
                                if (code == 0) {
                                    var data = hotTop.data;
                                    if ($('#nav_tab')) {
                                        var lineHtml = '<a class="line_r" href="javascript:;">热点知识</a>' + $('#nav_tab').html()
                                        $('#nav_tab').html(lineHtml);
                                        var tabDiv = '<div class="side-tab" style="display:none"><div class="service">';
                                        $.each(data, function (i, item) {
                                            $F.log(item.question);
                                            tabDiv += '<a class="hotTop" href="####" ><span>' + item.question + '</span></a>';
                                        })
                                        tabDiv += '</div></div>';
                                        $('.side-main').prepend(tabDiv);

                                        $("#nav_tab a").off('click').on('click', function () {
                                            $('.side-nav a').removeClass('cur');
                                            $(this).addClass('cur');

                                            $('.side-main .side-tab').hide();
                                            var idx = $('.side-nav a').index(this) + 1;
                                            $('.side-main .side-tab:nth-child(' + idx + ')').show();
                                        });

                                        $(".hotTop").on("click", function () {
                                            sendComment(this.text)
                                        })

                                        $('#nav_tab a:nth-child(1)').click();
                                    }
                                }
                            }
                        }
                    } else {
                        $F.log('获取热点知识失败: ' + JSON.stringify(data));
                    }
                } else {
                    $F.log('获取热点知识失败: ' + JSON.stringify(data));
                }
            });
        },
        loadResource: function () {
            var head = $config.queue;
            document.title = i18n.page.title;
            UI.ratePc();
            if ("module" == $config.theme) {
                UI.loadLogo(head);
                UI.loadHeadTitle(head);
                $("#workTime b").html(i18n.page.workTime);
                UI.loadWorkTime(head);
                $("#changeModule").html(i18n.page.changeModule);
                UI.loadChangeCustomer(head);
                $("#leaveMsg_div").html('<span>' + i18n.page.leaveMsgTip + '</span>');
                UI.loadHeadLm(head);
                $("#close_div").html(i18n.page.endChat); //关闭按钮
                $("#back_div").html(i18n.page.backChat); //关闭按钮
                UI.loadQCScan(head);
                $('#chatTime').hide();
                //加载跑马灯
                if (head.marquee) {
                    if (head.marquee == '-1') {
                        $('.scroll').hide();
                    } else {
                        $F.loadingMarquee(head.marquee);
                    }
                }
                //加载头部的链接
                if (head.shortCutLink) {
                    if (head.shortCutLink == '-1') {
                        $('#navBox').hide();
                    } else {
                        $F.loadingHeadLink(head.shortCutLink);
                    }
                }
            } else {
                $("#headTitle").html(i18n.page.headTitle);
                $("#workTime b").html(i18n.page.workTime);
                $("#changeModule").html(i18n.page.changeModule);
                $("#leaveMsg_div").html(i18n.page.leaveMsgTip);
            }
            $("#close_div").html(i18n.page.endChat); //关闭按钮
            $("#back_div").html(i18n.page.backChat); //关闭按钮
            $("#sendBtn_div").html(i18n.page.send);//发送按钮
            $("#es_li").html(i18n.page.enterSend);//选择发送的方式
            $("#ces_li").html(i18n.page.ctrlEnterSend);//选择发送的方式
            $("#words").html(i18n.page.wordsCountHint); //字数限制
            $("#rating_img").attr("alt", i18n.page.rating);
            $("#words2").html(i18n.page.wordsCountHint);
            $("#ratingSubmit").html(i18n.page.submit);
            $("#tips").html($config.queue.hotPhone || i18n.page.hotPhone);
            $(".auto-auswer span").text(i18n.pc.robotTitle);
            $(".customer-service span").text(i18n.pc.customerTitle);
            $(".button-load-talk span").text(i18n.page.loadHistory)
            $(".talking").text(i18n.page.isTalking);
            $(".voice-cancel").text(i18n.page.talkCancel);
            $(".voice-enter").text(i18n.page.talkSure);
        }
    };
    //清除显示满意度的定时任务
    clearShowRatingTimer = function () {
        clearTimeout(_showRatingTimer);
    }
    var endUrl = "";
    var endSessionPrint = false;
    var nomalNoticeMsgTimes = config.common.nomalNoticeMsgTimes;
    //历史记录
    var _fromMessageId = 0;
    var showHistoryMsgTip = false;
    var _showHistoryChating = false;
    var _originalTitle = document.title;
    var queueObj = config.queue;
    var queueArr = new Array();
    var _tempMessageSendTimer;
    var _firstShowHis = true;
    var firstClickHis = true;
    var _lastmessageId = 0;
    var messageMap = {};
    var _startTime = 0;
    var _barcodeMouseMove = true;
    var noticetype = 0;

    window.preMsg = "";

    window.ToolsToSendMsg = function (msg) {
        chatEditor.html(msg);
        $("#sendBtn_div").click();
    }

    window.ToolsToSendNotice = function (msg) {
        $("#clientResponseDiv", window.parent.document).append('<div id=\"waitingForAcceptInChatView\"><div class=\"no-bg no-green\"><div class=\"notice\">' + msg + '</div></div></div>');
    }

    // $COMM.showOriginImage = function(img, contextPath) {
    //     var allImgs = $('.message img:not(.avatar,.qqemoji,.standard-emoji,.location,.custom-emoji)');
    //     if (!contextPath)
    //         contextPath = '';
    //     var index = 0, urls = [];
    //     if (allImgs && allImgs.length > 0) {
    //         allImgs.each(function(i, v) {
    //             if (v === img) {
    //                 index = i;
    //             }
    //             var url = $(v).attr('data-url') || v.src;
    //             urls.push(url);
    //         });
    //     } else {
    //         var url = $(img).attr('data-url') || img.src;
    //         urls.push(url);
    //     }
    //
    //     window.open(contextPath + 'imgViewer.html?url=' + urls.join(',') + '&index=' + index, "_imgWin", "menubar=no,toolbar=no,titlebar=no,status=no");
    //
    // }

    function speakingStatu(colorChange, pln) {
        if (colorChange) {
            $F.log("录音中…………, powerLevel[" + pln + "]");
        }
    }


    function loadBusinessKeys(id, type) {
        $F.doAjaxCall(Constants.ajaxURL, {
            requestType: "businessKey",
            sessionId: $config.sessionId,
            id: id || '',
            type: type || ''
        }, function (data) {
            if (data.status == 'success') {
                $F.log("loadBusinessKeys: " + JSON.stringify(data));
                if (data.businessKeys) {
                    var businessKeys = data.businessKeys;
                    if (businessKeys.length > 0) {
                        var keysHtml = '<ul>';
                        if (bussinessHistoryKeys.length > 0) {
                            keysHtml += '<li class="key-back"><i class="fas fa-reply"></i></li>';
                        }
                        $.each(businessKeys, function (i, businessKey) {
                            keysHtml += '<li data-id="' + businessKey.id + '" data-type="' + businessKey.type + '" class="key-text">' + businessKey.name + '</li>';
                        })
                        keysHtml += '</ul>';
                        $(".keys-space").css("display", "flex");
                        $(".keys-space").html(keysHtml);
                        tbResize();
                    }
                }
            } else {
                $F.log('获取热点知识失败: ' + JSON.stringify(data));
            }
        });
    }

    var recOpen = function () {//一般在显示出录音按钮或相关的录音界面时进行此方法调用，后面用户点击开始录音时就能畅通无阻了
            rec = null;
            wave = null;
            recBlob = null;
            var colorChange = true;
            var newRec = Recorder({
                type: _voiceFormat, sampleRate: _voiceRate, bitRate: 16 //mp3格式，指定采样率hz、比特率kbps，其他参数使用默认配置；注意：是数字的参数必须提供数字，不要用字符串；需要使用的type类型，需提前把格式支持文件加载进来，比如使用wav格式需要提前加载wav.js编码引擎
                , onProcess: function (buffers, powerLevel, bufferDuration, bufferSampleRate, newBufferIdx, asyncEnd) {
                    //录音实时回调，大约1秒调用12次本回调
                    speakingStatu(colorChange, powerLevel);
                }
            });

            // createDelayDialog(); 我们可以选择性的弹一个对话框：为了防止移动端浏览器存在第三种情况：用户忽略，并且（或者国产系统UC系）浏览器没有任何回调，此处demo省略了弹窗的代码
            newRec.open(function () {//打开麦克风授权获得相关资源
                // dialogCancel(); //如果开启了弹框，此处需要取消
                rec = newRec;
                //此处创建这些音频可视化图形绘制浏览器支持妥妥的
                // wave = Recorder.FrequencyHistogramView({elem: ".recwave"});
                $F.log("已打开录音，可以点击录制开始录音了");
                _readyToAudio = true;
                recStart();
            }, function (msg, isUserNotAllow) {//用户拒绝未授权或不支持
                // dialogCancel(); //如果开启了弹框，此处需要取消
                _readyToAudio = isUserNotAllow;
                $F.log((isUserNotAllow ? "UserNotAllow，" : "") + "打开录音失败：" + msg);
            });

            window.waitDialogClick = function () {
                // dialogCancel();
                _readyToAudio = false;
                $F.log("打开失败：权限请求被忽略，<span style='color:#f00'>用户主动点击的弹窗</span>");
            };
        },

        /**一般的模式录音: 开始录音**/
        recStart = function () {//打开了录音后才能进行start、stop调用
            _voiceRunning = true;
            if (rec && Recorder.IsOpen()) {
                recBlob = null;
                rec.start();
                $F.log("已开始录音...");
                var widthTimes = 0;
                var width = $(".voiceBox").width() / 60;
                _voiceTimer = setInterval(function () {
                    widthTimes += 1;
                    $(".voiceProgress").css("width", widthTimes * width + 'px');
                    $F.log(widthTimes);
                    if (widthTimes > 60) {
                        clearInterval(_voiceTimer);
                        recStop();
                    }
                }, 1000);
                setTimeout(function () {
                    recStop();
                }, 60000)
            } else {
                $F.log("未打开录音");
            }
            ;
        },
        /**一般的模式录音: 结束录音，得到音频文件**/
        recStop = function (flag) {
            _voiceRunning = false;
            clearInterval(_voiceTimer);
            if (!(rec && Recorder.IsOpen())) {
                $F.log("未打开录音");
                return;
            }
            rec.stop(function (blob, duration) {
                if (flag) {
                    $F.log("已录制mp3：" + duration + "ms " + blob.size + "字节，可以点击播放、上传了");
                    var form = new FormData();
                    form.append("file", blob, "recorder." + _voiceFormat); //和普通form表单并无二致，后端接收到upfile参数的文件，文件名为recorder.mp3
                    //已经拿到blob文件对象想干嘛就干嘛：立即播放、上传
                    $.ajax({
                        url: 'uploadh5' //上传接口地址
                        , type: "POST"
                        , contentType: false //让xhr自动处理Content-Type header，multipart/form-data需要生成随机的boundary
                        , processData: false //不要处理data，让xhr自动处理
                        , data: form
                        , success: function (data) {
                            $F.log("上传成功", data);
                            if (data.status === 'success') {
                                var remoteUrl = data.url;
                                var fName = name.replace(/\\/gi, '/');
                                fName = fName.substring(fName.lastIndexOf('/') + 1);
                                var classVoice = 'voice_class_' + new Date().getTime();
                                var content = '<div class="message-voice" data-url="' + remoteUrl + '"  data-type="baidu" data-length="' + duration / 1000 + '" data-content="' + duration + '" ></div>' +
                                    '<div class="voice-recognition ' + classVoice + ' hide"></div>';
                                $F.appendTextToDiv("clientResponseDiv", $F.getDisplayMessage($config.client.clientId, '', content));
                                var sendcontent = '<div class=\\\"message-voice ' + classVoice + '\\\" data-length=\\\"' + duration / 1000 + '\\\" data-url=\\\"' + data.url + '\\\"></div>';
                                //对语音文件进行翻译
                                var recognition = "";
                                var voiceBlob = blob;
                                var fileReader = new FileReader();
                                fileReader.onload = function (e) {
                                    var base64Code = this.result;
                                    $.ajax({
                                        url: 'recognition.do' //上传接口地址
                                        , type: "POST"
                                        , contentType: "application/json" //让xhr自动处理Content-Type header，multipart/form-data需要生成随机的boundary
                                        , processData: false //不要处理data，让xhr自动处理
                                        , data: JSON.stringify({
                                            voiceData: base64Code.split(",")[1],
                                            voiceUri: remoteUrl,
                                            voiceType: _voiceFormat,
                                            length: duration
                                        })
                                        , success: function (data) {
                                            var recognition = '';
                                            if (data.status === "success") {
                                                recognition = data.recognition
                                            } else {
                                                recognition = i18n.page.recognition.error;
                                            }
                                            recognition = recognition ? recognition : i18n.page.recognition.error;
                                            $('.' + classVoice).text(recognition);
                                            sendcontent += '<div class=\\\"wechat-voice-recognition\\\">' + recognition + '</div>';
                                            $F.doAjaxCall(Constants.ajaxURL, "requestType=send&data=" + $F.getPostMessageSentInfoJSON(encodeURIComponent(sendcontent)));
                                        }
                                        , error: function (s) {
                                            sendcontent += '<div class=\\\"wechat-voice-recognition\\\">' + i18n.page.recognition.error + '</div>';
                                            $F.doAjaxCall(Constants.ajaxURL, "requestType=send&data=" + $F.getPostMessageSentInfoJSON(encodeURIComponent(sendcontent)));
                                        }
                                    })
                                };
                                fileReader.readAsDataURL(voiceBlob);
                            } else {
                                alert(i18n.page.uploadFile.fail.format(data.message));
                            }
                        }
                        , error: function (s) {
                            $F.error(i18n.page.uploadFile.fail.format(s));
                        }
                    });
                }
            }, function (msg) {
                $F.log("录音失败:" + msg);
            })
        }

    KindEditor.ready(function (K) {
        var items = config.items;
        if ($.inArray("hisTop", items) == -1) {
            $(".hischat").hide();
            if ($config.queue.historyLoad != -1) {
                $(".button-load-talk").show();
            }
            showHistoryMsgTip = true;
        } else {
            items.splice($.inArray("hisTop", items), 1);
            if ($config.queue.historyLoad != -1) {
                $(".hischat").css("display", "block");
            }
        }
        if ($config.allowSaveChat) {
            if ($.inArray("saveChat", items) == -1) {
                if ($.inArray("rating", items) == -1) { //rating
                    items.push("saveChat");
                } else {
                    items.splice($.inArray("rating", items), 1);
                    items.push("saveChat");
                    items.push("rating");
                }

            }
        } else {
            if ($.inArray("saveChat", items) > -1) {
                items.splice($.inArray("saveChat", items), 1);
            }
        }
        if ($config.queue.allowVoice) {
            // items.push();
            if (!$.inArray("voice", items)) {
                items.splice(items.length - 2, 0, "voice");
            }
        } else {
            if (!$.inArray("voice", items)) {
                items.remove("voice");
            }
        }
        if ($config.queue.historyLoad == 1) $(".button-load-talk").hide();

        if (_allowAttachment) {
            if ($.inArray("sendAttachment", items) == -1) {
                if ($.inArray("rating", items) == -1) { //rating
                    items.push("sendAttachment");
                } else {
                    items.splice($.inArray("rating", items), 1);
                    items.push("sendAttachment");
                    items.push("rating");
                }
            }
        } else {
            if ($.inArray("sendAttachment", items) > -1) {
                items.splice($.inArray("sendAttachment", items), 1);
            }
        }


        window.K = K;
        window.chatEditor = K.create('#clientMessageBox', {
            themeType: $config.theme,
            allowPreviewEmoticons: false,
            allowUpload: false,
            items: items,
            filterMode: true,//是否开启过滤模式
            htmlTags: {
                font: ['id', 'class', 'color', 'size', 'face', '.background-color'],
                div: [
                    'id', 'class', 'align', '.border', '.margin', '.padding', '.text-align', '.color',
                    '.background-color', '.font-size', '.font-family', '.font-weight', '.background',
                    '.font-style', '.text-decoration', '.vertical-align', '.margin-left'
                ],
                a: ['id', 'class', 'href', 'target', 'name'],
                embed: ['id', 'class', 'src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
                img: ['id', 'class', 'src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'],
                'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6': [
                    'id', 'class', 'align', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.background',
                    '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.text-indent', '.margin-left'
                ],
                pre: ['id', 'class'],
                hr: ['id', 'class', '.page-break-after'],
                'br,tbody,tr,strong,b,sub,sup,em,i,u,strike,s,del': ['id', 'class'],
                iframe: ['id', 'class', 'src', 'frameborder', 'width', 'height', '.width', '.height']
            },
            newlineTag: 'br',
            width: '100%',
            height: '125px',
            minWidth: '300px',
            minHeight: '90px',
            resizeType: 0,
            afterCreate: function () {
                var self = this;
                K.ctrl(self.edit.doc, 13, function () {
                    if (_sessionActive) {
                        if (_sendShortcutType == 1) {
                            $("#sendBtn_div").click();
                        }
                    }
                });

                $(self.edit.doc).on('paste', function (e) {
                    pasteImg(e);
                });

                K(self.edit.doc).keydown(function (event) {
                    if (_sendShortcutType == 0) {
                        if (event.which == 13) {
                            event.preventDefault();
                            if (!event.ctrlKey) {
                                $("#sendBtn_div").click();
                            } else {
                                self.insertHtml('<br>')
                            }
                        }
                    }
                    if (!_countAvailable) {
                        if (event.which != 46 && event.which != 8) {
                            event.preventDefault();
                            return false;
                        }
                    }
                });

                if (config.rating) {
                    $(".ke-toolbar > span").last()
                        .css("float", "right")
                        .css("width", "130px").find("span")
                        .css("font-size", "14px")
                        .css("line-height", "2")
                        .css("width", "130px")
                        .css("text-align", "center")
                        .text(i18n.page.rating);
                }
                initJavaScript();
            },
            afterFocus: function () {
                _clientMessageBoxInFocus = true;
            },
            afterBlur: function () {
                _clientMessageBoxInFocus = false;
            },
            afterChange: function () {
                this.sync();
                var len = this.count("text");
                _countAvailable = countWords(len, "words");
                if (_sessionActive) {
                    if (_affectEditorChange) {
                        if (_tempMessageSendTimer) {
                            clearTimeout(_tempMessageSendTimer);
                        }
                        if ('' == Constants.agent.id) {
                            var messageText = this.text();
                            if (_privousText != messageText) {
                                if (messageText.length > 0) {
                                    _privousText = messageText;
                                    _privousText = _privousText.replace(/\r\n/g, '').replace(/\n\r/g, '').replace(/\r/g, '').replace(/\n/g, '').replace(/\b/g, '');
                                    var startTimes = new Date().getTime();
                                    $F.doAjaxCall(Constants.ajaxURL, {
                                        requestType: "send",
                                        data: $F.getPostMessageSentInfoJSON(_privousText, "getQuestionRecommendation")
                                    }, function (response) {
                                        $F.log("Response from send : " + JSON.stringify(response) + ", times:" + (new Date().getTime() - startTimes));
                                        var sendResponse = response.sendResponse;
                                        if (sendResponse) {
                                            var feedbackMessage = sendResponse.feedbackMessage;
                                            if (feedbackMessage) {
                                                if (typeof feedbackMessage == 'string') {
                                                    feedbackMessage = JSON.parse(feedbackMessage);
                                                }
                                                var robotType = $config.queue.robotEngineConfig.type;
                                                if (robotType == 9) {
                                                    if (feedbackMessage.isSuccess == 1) {
                                                        feedbackMessage = feedbackMessage.questionList
                                                    }
                                                }
                                                if (feedbackMessage.length > 0) {
                                                    var ulHtml = '<h4>' + i18n.page.guessYouWantAsk + '</h4><ul>';
                                                    $.each(feedbackMessage, function (i, message) {
                                                        ulHtml += '<li><span><a>' + message + '</a></span></li>'
                                                    });
                                                    ulHtml += '</ul>';
                                                    $('.robot-ques').html(ulHtml);
                                                    $('.robot-ques').show();
                                                    $('.robot-ques').css('top', -($('.robot-ques').height() + 40));
                                                }
                                            }
                                        }
                                    });
                                    setTimeout(function () {
                                        $('.robot-ques').hide();
                                    }, 4000);
                                }
                            }
                        } else {
                            var messageText = this.text();
                            var doSendTempMessage = function () {
                                if (_privousText != messageText) {
                                    _privousText = messageText;
                                    _privousText = _privousText.replace(/\r\n/g, '').replace(/\n\r/g, '').replace(/\r/g, '').replace(/\n/g, '').replace(/\b/g, '');
                                    $F.doAjaxCall(Constants.ajaxURL, {
                                        requestType: "send",
                                        data: $F.getPostMessageSentInfoJSON(_privousText, "postTempMessage")
                                    });
                                }
                            }
                            _tempMessageSendTimer = setTimeout(function () {
                                doSendTempMessage();
                            }, 3000);
                        }
                        if (messageText.length > 0) {
                            $("#sendBtn_div").addClass("active");
                        } else {
                            $("#sendBtn_div").removeClass("active");
                        }
                        //如果是机器人模式，并且有相关问题搜索的接口就需要发送消息给机器人的相关内容
                    }
                    //发送正在输入提示
                    var now = new Date().getTime();
                    if ((now - _lastTypingNotificationTime) >= (_typingNotificationDelay * 1000)) {
                        _lastTypingNotificationTime = now;
                        $F.doAjaxCall(Constants.ajaxURL, {
                            requestType: 'sendTypingNotification',
                            sessionId: $config.sessionId
                        });
                    }
                }
            }
        });
        if (_allowAttachment) {
            K.plugin('sendAttachment', function (K) {
                var editor = this, name = 'sendAttachment';
                editor.clickToolbar(name, function () {
                    sendAttachment();
                });
            });
        }

        K.plugin('chathis', function (K) {
            var editor = this, name = 'chathis';
            editor.clickToolbar(name, function () {
                _showHistoryChating = true;
                showHistory(function (time, html) {
                    if (html) {
                        $F.prependTextToDiv("clientResponseDiv", "<span class='his_time'>" + $F.getLocalTime(postTime) + "</span>");
                        $F.prependTextToDiv("clientResponseDiv", html);
                    }
                });
            });
        });

        K.plugin('rating', function (K) {
            var editor = this, name = 'rating';
            editor.clickToolbar(name, function () {
                judgeShowRate(Constants.rate.rateType.CLIENT_SEND);
            });
        });

        K.plugin('saveChat', function (K) {
            var editor = this, name = 'saveChat';
            editor.clickToolbar(name, function () {
                saveChat();
            });
        });

        K.plugin('capture', function (K) {
            var editor = this, name = 'capture';
            editor.clickToolbar(name, function () {
                if ($config.sessionId != -1 && _sessionActive) {
                    CaptureUtil.capture(1, function (data) {
                        if (data.code == 1) {
                            var img = '<img src="' + data.result.url + '" title="' + data.result.name + '"  style="max-width: 300px; max-height: 300px;" />';
                            editor.insertHtml(img);
                        }
                    });
                }
            });
        });

        /**常用地址在工具栏的显示 */
        K.plugin('navBox', function (K) {
            var editor = this, name = 'navBox';
            if ($.inArray("navBox", items) > -1) {
                $("#navBox").hide();
            }
            editor.clickToolbar(name, function () {
                var items = config.items;
                var toolLink = $(".tool-link");
                if (toolLink.css("display") == "none") {
                    toolLink.css("display", "block");
                } else {
                    toolLink.css("display", "none");
                }
            });

            $(".tool-link").hover(function () {
                $(this).show();
            }, function () {
                $(this).hide();
            })
        });
        if ($config.queue.allowVoice) {
            /**
             * 发送语音
             */
            K.plugin('voice', function (K) {
                var editor = this, name = 'voice';
                editor.clickToolbar(name, function () {
                    $(".voiceBox").toggle();
                    if (_voiceRunning) {
                        recStop(false);
                    } else {
                        if (voiceInit) {
                            recOpen();
                        } else {
                            recStart();
                        }
                    }
                });
            });
        }

        K.lang({
            sendAttachment: i18n.scripts.sendAttachment,
            saveChat: i18n.scripts.saveChat,
            chathis: i18n.scripts.chathis,
            navBox: i18n.scripts.navBox,
            rating: i18n.scripts.rating,
            "emoticons-image": i18n.scripts.emoticonsImage,
            capture: i18n.scripts.capture,
            voice: i18n.page.audio.alt
        });

        $(".voice-cancel").on("click", function () {
            recStop(false);
        })

        $(".voice-enter").on("click", function () {
            recStop(true);
        })

        $(".voiceBtn").on("click", function () {
            $(".voiceBox").toggle();
        })

        var editorDoc = $(K.edit.doc);
        var doc = $(document);

        // 处理插入拖出效果
        function handleDragEnter(evt) {
            evt.stopPropagation();
            evt.preventDefault();
        }

        function handleDragLeave(evt) {
            evt.stopPropagation();
            evt.preventDefault();
        }

        // 处理文件拖入事件，防止浏览器默认事件带来的重定向
        function handleDragOver(evt) {
            evt.stopPropagation();
            evt.preventDefault();
        }

        if (window.FileReader) {
            function handleDrop(evt) {
                evt.stopPropagation();
                evt.preventDefault();
            }

            function isImage(type) {
                switch (type) {
                    case 'image/jpeg':
                    case 'image/png':
                    case 'image/gif':
                    case 'image/bmp':
                    case 'image/jpg':
                        return true;
                    default:
                        return false;
                }
            }

            // 处理拖放文件列表
            function handleFileSelect(evt) {
                evt = evt.originalEvent;
                evt.stopPropagation();
                evt.preventDefault();
                var files = evt.dataTransfer.files;
                for (var i = 0, f; f = files[i]; i++) {
                    var t = f.type ? f.type : 'n/a',
                        reader = new FileReader(),
                        isImg = isImage(t),
                        img;
                    // 处理得到的图片
                    if (isImg) {
                        reader.onload = (function (theFile) {
                            return function (e) {
                                uploadToServer(theFile, e.target.result);
                            };
                        })(f)
                        reader.readAsDataURL(f);
                    } else {
                        alert(i18n.page.fileSelect);
                    }
                }
            }

            function pasteImg(event) {
//              editorDoc.on('paste', function (event) {
                event.stopPropagation();
                event.preventDefault();
                var cd = event.clipboardData || event.originalEvent.clipboardData || window.clipboardData;
                if (cd) {
                    if ('' != Constants.agent.id && _allowAttachment) {
                        var items = cd.items;
                        for (index in items) {
                            var item = items[index];
                            if (item.kind === 'file') {
                                var blob = item.getAsFile();
                                var filename = blob.name;
                                var hz = filename.substring(filename.lastIndexOf(".") + 1);
                                var reader = new FileReader();
                                reader.filename=filename;
                                reader.hz=hz;
                                reader.onload = function (event) {
                                    uploadToServer({name: event.target.filename, type: event.target.hz }, event.target.result);
                                };
                                reader.readAsDataURL(blob);
                            }
                        }
                    }

                    var pastedData = cd.getData('Text');
                    if (pastedData) {
                        pastedData = pastedData.trim()
                            .replaceAll('\r\n', '<br>')
                            .replaceAll('\n\r', '<br>')
                            .replaceAll('\r', '<br>')
                            .replaceAll('\n', '<br>')
                            .replaceAll('\b', ' ')
                            .replaceAll(' ', '&nbsp');
                        if ($config.queue && $config.queue.allowShowHtml) {
                            pastedData = pastedData.replaceAll(/</g, "&lt;").replaceAll(/>/g, "&gt;");
                        } else {
                            pastedData = pastedData.replaceAll(/<.*?>/g, "").replaceAll(/&lt;.*?&gt;/g, "").replaceAll('&lt;', "").replaceAll('&gt;', "");
                        }
                        var activeElementId = document.activeElement.id;
                        $F.log("active element " + '' == activeElementId);
                        if (activeElementId) {
                            var nowCount = pastedData.length + $("#" + activeElementId).val().length;
                            var allowCount = parseInt(i18n.page.maxWrite);
                            if (nowCount < allowCount) {
                                $("#" + activeElementId).val($("#" + activeElementId).val() + pastedData);
                            }
                        } else {
                            chatEditor.insertHtml(pastedData);
                        }

                    }
                }
            }

            editorDoc.on('dragenter', handleDragEnter);
            editorDoc.on('dragover', handleDragOver);
            editorDoc.on('drop', handleFileSelect);
            editorDoc.on('dragleave', handleDragLeave);
            doc.on('dragenter', handleDragEnter);
            doc.on('dragover', handleDragOver);
            doc.on('drop', handleFileSelect);
            doc.on('dragleave', handleDragLeave);
            editorDoc.on('paste', pasteImg);
            $('#pjwords').on('paste', pasteImg);
        }

        var uploadToServer = function (oldFile, newFile) {
            //submit formData using $.ajax      
            //var fileName = new Date().getTime()+"--" + oldFile.name;
			console.log("上传文件名:" + oldFile.name + " 拓展名:" + oldFile.type);
            var fileName = oldFile.name.substring(0,oldFile.name.indexOf(".")) + "-" + new Date().getTime() + oldFile.name.substring(oldFile.name.indexOf("."));
			console.log("Server文件名:" + fileName);
            $F.doAjaxCall('uploadDataURI', {
                filename: fileName,
                filetype: oldFile.type,
                dataURI: newFile
            }, function (data) {
                if (data && data.url) {
                    var content = "";
                    if ($F.isImage(fileName)) {
                        content = '<img src = "' + data.url + '" alt = "' + oldFile.name + '" style="max-width: 300px; max-height: 300px;">';
                    } else {
                        content = '<a href = "' + data.url + '" target = "_blank" class="attachment">' + oldFile.name + ' </a>';
                    }
                    chatEditor.insertHtml(content);
                } else {
                    alert(i18n.page.uploadFile.fail.format(""));
                }
            }, function () {
                $F.log(i18n.page.uploadFile.fail.format(""));
            })
        }
    });

    function pullfailToAgent() {
        if (!$config.queue.robotEngineConfig) {
            _sessionActive = false;
        } else {
            UI.robot();
            _chatRequestId = -1;
        }
    }

    function tbResize() {
        var wHeight = document.documentElement.clientHeight || document.body.clientHeight;
        var iWWidth = document.documentElement.clientWidth || document.body.clientWidth;
        var iScreenWidth = screen.availWidth / 2;
        var mainDiv = $(".main");
        var mainMarginTop = parseInt(mainDiv.css('margin-top').replace('px', ''));
        var mainMarginBottom = parseInt(mainDiv.css('margin-bottom').replace('px', ''));
        var mainMarginLeft = parseInt(mainDiv.css('margin-left').replace('px', ''));
        var mainMarginRight = parseInt(mainDiv.css('margin-right').replace('px', ''));
        if (iWWidth < iScreenWidth) {
            mainDiv.width(iScreenWidth - mainMarginLeft - mainMarginRight);
            window.resizeTo(screen.availWidth / 2, screen.availHeight / 2);
        } else {
            mainDiv.width(iWWidth - mainMarginLeft - mainMarginRight);
        }
        mainDiv.height(wHeight - mainMarginTop - mainMarginBottom);
        var header = $('.head');
        var headerHeight = 0;
        if (header && header.css('display') != 'none') {
            headerHeight = header.outerHeight(true);
        }
        $(".body").outerHeight($(".main").outerHeight() - headerHeight);
        var leftContainer = $('.left-container');
        var rightContainer = $('.menu-container');
        var chatContainer = $('.chat-container');
        var mainHeight = $(".body").outerHeight();
        if (leftContainer && leftContainer.css('display') != 'none') {
            leftContainer.css('top', headerHeight);
            leftContainer.outerHeight(mainHeight);
            chatContainer.css('margin-left', leftContainer.outerWidth());
        } else {
            leftContainer.css('margin-right', 0);
        }
        if (rightContainer && rightContainer.css('display') != 'none') {
            // rightContainer.css('top', headerHeight);
            rightContainer.outerHeight(mainHeight);
            chatContainer.css('margin-right', rightContainer.outerWidth());
        } else {
            chatContainer.css('margin-right', 0);
        }
        chatContainer.outerHeight(mainHeight);
        $("#talkBox").outerHeight(parseInt(chatContainer.outerHeight() -
            ($(".scroll").is(":hidden") ? 0 : $(".scroll").height()) -
            ($(".bar").is(":hidden") ? 0 : $('.bar').height()) -
            ($(".keys-space").is(":hidden") ? 0 : $('.keys-space').height()) -
            $('.c-main-btn').height() -
            $('.c-p').outerHeight()));
    }

    function generateTimeNumber() {
        var date = new Date().format("yyyyMMddHHmmss");
        return date
    }

    $(function () {
        bindOnBeforLoad();// 绑定关闭tab和浏览器事件
        $(".his-title, .hischat").text(i18n.page.historyTitle);
        if (document.all) {
            $("a[href='javascript:;']").on("click", function (e) {
                e.preventDefault();
            });
        }
        //禁止使用F5刷新功能
        $(document).on('keydown', function (e) {
            e = window.event || e;
            var keycode = e.keyCode || e.which;
            if (e.shiftKey && e.altKey && e.keyCode == 90) { //截图快捷键
                //隐藏当前窗口截图
                if ($config.sessionId != -1 && _sessionActive) {
                    CaptureUtil.capture(0, function (data) {
                        if (data.code == 1) {
                            var img = '<img src="' + data.result.url + '" title="' + data.result.name + '"  style="max-width: 300px; max-height: 300px;" />';
                            chatEditor.insertHtml(img);
                        }
                    });
                    e.stopPropagation();
                    e.preventDefault();
                }

            } else if (e.shiftKey && e.altKey && e.keyCode == 65) {
                //不隐藏当前窗口截图
                if ($config.sessionId != -1 && _sessionActive) {
                    CaptureUtil.capture(1, function (data) {
                        if (data.code == 1) {
                            var img = '<img src="' + data.result.url + '" title="' + data.result.name + '"  style="max-width: 300px; max-height: 300px;" />';
                            chatEditor.insertHtml(img);
                        }
                    });
                    e.stopPropagation();
                    e.preventDefault();
                }

            } else if (e.altKey || keycode >= 112 && keycode <= 123) {
                if (window.event) {// ie
                    try {
                        e.keyCode = 0;
                    } catch (e) {
                    }
                    e.returnValue = false;
                } else {// ff
                    e.preventDefault();
                }
            }
        }).on("click", ".key-text", function () {
            var type = $(this).data("type"), key = $(this).data("key"), disable = $(this).data("disable") || '' , once = $(this).data("once") || '' ;
            if (disable) return;
            else {
                if (once) $(this).data("disable", 1).addClass("btn-disable")
                    .siblings().data("disable", 1).addClass("btn-disable");
                if (type == 3) {
                    sendCommentWithSearchKey($(this).text(), key || '', 'bussiness-key');
                } else if (type == 'text') {
                    sendCommentWithSearchKey($(this).text(), key || '', 'bussiness-key');
                } else if (type == 'action') {
                    sendCommentWithSearchKey($(this).data("text"), key || '', 'bussiness-key');
                } else if (type == 'link') { //链接 点击跳转地址
                    window.open($(this).data("value"));
                } else if (type == 'message') {
                    sendCommentWithSearchKey($(this).data("value") || $(this).text(), key || '', 'bussiness-key');
                } else {
                    bussinessHistoryKeys.push({
                        id: $(this).data("id"),
                        type: type
                    })
                    loadBusinessKeys($(this).data("id"), type);
                }
            }
        }).on("click", ".key-back", function () {
            var busiKeysSize = bussinessHistoryKeys.length;
            if (busiKeysSize == 1) {
                bussinessHistoryKeys.pop();
                loadBusinessKeys("", "");
            } else if (busiKeysSize > 1) {
                var bussinessKey = bussinessHistoryKeys[busiKeysSize - 2];
                bussinessHistoryKeys.pop();
                loadBusinessKeys(bussinessKey.id, bussinessKey.type);
            }
        }).on("click", "input[name]", function () {
            $F.log($(this).data("sigle"));
            $.each($("." + $(this).data("sigle")), function (i, sigle) {
                // $(sigle).removeAttr("checked");
            })
            $(this).attr("checked", "true");
        });

        /**
         * 用来对UI进行切换，
         */
        $('.change-ui').on("click", function () {
            if ($('.main').hasClass("default")) {
                $('.main').removeClass("default");
            } else {
                $('.main').addClass("default");
            }
        });


        $('.barcode').mouseenter(function () {
            if (_barcodeMouseMove) {
                _barcodeMouseMove = false;
                setTimeout(function () {
                    _barcodeMouseMove = true;
                }, 2000)
                $('.barcade-img').show();
                var src = $(".barcade-img").data("src");
                if (src == '1') {
                    $('.barcade-img').children().attr('src', _contextPath + '/client/gencode.do?queue={0}&sessionId={1}'.format($config.queueId, $config.sessionId));
                } else {
                    $('.barcade-img').children().attr('src', src);
                }
            }
        });

        $('.barcode').mouseout(function () {
            if (!_barcodeMouseMove) {
                _barcodeMouseMove = true;
            }
        });

        $(".service-item").on('click', function () {
            $(".serviceType").addClass("hidden");
            var queueId = $(this).data('queue');
            var oldSkin = $config.queue.skin;
            $config.queue = _queueForConfig[queueId];
            $config.robotEngineConfig = _queueForConfig[queueId].robotEngineConfig;
            $ROBOT.init($config.robotEngineConfig);
            //切换完之后修改UI
            if ($config.queue.skin != oldSkin) {
                var links = document.getElementsByTagName('link');
                $.each(links, function (i, link) {
                    if (link && link.href.indexOf('skin') > -1) {
                        var head = document.getElementsByTagName('head')[0];
                        var skinLink = document.createElement("link");
                        skinLink.setAttribute("rel", "stylesheet");
                        skinLink.setAttribute("type", "text/css");
                        skinLink.setAttribute("href", '/webchat/jsp/standard/resource/skin/' + $config.queue.skin + '.css?v=1624599224566');
                        links[i].parentNode.removeChild(links[i]);
                        head.appendChild(skinLink);
                    }
                })
            }
            createChat(queueId);
        })
        // 满意度入口按钮

        $('.barcode,.barcade-img').mouseout(function () {
            $('.barcade-img').hide();
        });

        $F.loadingMargueeImg(config.margueeImg);

        $(window).on('unload', callbackOnWindowClose);

        //chatEditor.readonly();
        if (Constants.robot.robotFirst) {
            UI.robot();
            queueArr = $F.loadingQuee(queueObj, function () {
                $('.queue li').on('click', function () {
                    if (queueObj.click) {
                        createChat($(this).attr('queue'));
                        UI.hideChangeModule();
                        $(this).parents('.queue').html('<em>' + i18n.page.queue.select.format('[' + $(this).text() + ']') + '</em>');
                    }
                });
            });
        } else {
            queueArr = null;
            UI.cuestomerService();
        }

        //选择发送快捷方式
        $("#way_btn").on("click", function () {
            $("#way_tips").toggle();
        });

        //注册全屏按钮
        $(".large").on("click", function () {
            var $main = $(".main");
            if ($main.hasClass("largeDiv")) {
                $main.removeClass("largeDiv");
            } else {
                $main.addClass("largeDiv");
            }
            tbResize();
        });

        $("#way_tips").on("click", "li", function () {
            var _this = $(this);
            var way = $("#way_tips");
            if (!_this.hasClass("checked")) {
                _this.addClass("checked").siblings("li").removeClass("checked");
            }
            way.hide();
            if (this.id == "es_li") {
                _sendShortcutType = 0;
            } else {
                _sendShortcutType = 1;
            }
        });
        $("#leaveMsg_div").on("click", function () {
            if (Constants.lm.url) {
                bindOffBeforLoad();
                if ((Constants.lm.url).startWith('http'))
                    window.open(Constants.lm.url + '?queue=' + $config.queueId + '&clientid=' + Constants.client.clientId, Constants.lm.name);
                else
                    window.open('clientLeaveMessage.do' + '?queue=' + $config.queueId + '&clientid=' + Constants.client.clientId, Constants.lm.name + '&from=' + _from);
            }
        });

        //满意评价弹框 关闭
        $("#judge_pj_rg").on("click", ".pop-close, .pj_cancel", function () {
            $(".bg_cover, #judge_pj_rg, #discuss").hide();
            $F.rateAfter();
        });

        var pjCountAvailable = true;
        $("#pjwords").on("keyup", function () {
            var _this = $("#pjwords");
            var len = _this.val().length;
            pjCountAvailable = countWords(len, "words2");
        });

        $("#pjwords").on("keydown", function (e) {
            if (!pjCountAvailable) {
                e.preventDefault();
                return false;
            }
        });
        $("#pjwords").attr("maxlength", i18n.page.maxWrite);

        $("#close_div").click(function () {
            var tip = '';
            if (_sessionActive) {
                if ($ROBOT.notAllowShowRate(Constants.agent.id)) {
                    $config.rateSender = Constants.RateType.SHUT_SEND;
                    endSessionBtnClickHandler();
                } else {
                    if ($config.sessionId == '-1') {
                        tip = i18n.page.endChatTitle;
                    } else {
                        if ($config.sessionId > 0) {
                            tip = i18n.page.endChatTitleWhenUnChat;
                        } else {
                            tip = i18n.page.endChatTitleWhenHasEnd;
                        }
                    }
                    $F.showConfirm(tip, function () {
                        UI.rateClientShut();
                        //如果是配置先结束再弹出满意度就结束 反之 先弹出满意度
                        $config.rateSender = Constants.RateType.SHUT_SEND;
                        if (Constants.rate.client.rateOrEnd == Constants.rate.openRate.BEFORE_CLOSE) {
                            judgeShowRate(Constants.rate.rateType.CLIENT_CLOSE);
                            endSessionBtnClickHandler();
                        } else if (Constants.rate.client.rateOrEnd != Constants.rate.openRate.NOT_SHOW_RATE) {
                            judgeShowRate(Constants.rate.rateType.CLIENT_CLOSE);
                        } else {
                            endSessionBtnClickHandler();
                        }
                    });
                }
            } else {
                $F.hrefEndUrl();
            }
        });

        //右上角叉叉按钮
        $(".head-btn-container .close").on('click', function () {
            $("#close_div").click();
        });

        if ($config.queue.rightModuleInterface) {
            var rightInterface = $config.queue.rightModuleInterface;
            try {
                rightInterface = JSON.parse(rightInterface);
            } catch (e) {
            }
            if (typeof rightInterface == "object") { //是json数据
                infoToTabForRightModule(rightInterface)
            } else {
                if (rightInterface.startWith('http')) { //http开头的接口地址
                    $F.doAjaxCall(Constants.ajaxURL, {
                        requestType: 'getRightData',
                        queue: $config.queueId
                    }, function (data) {
                        if (data.status == 'success') {
                            infoToTabForRightModule(data.data)
                        }
                    });
                } else if (rightInterface.endWith('.json')) { //表示是以json为后缀的文件
                    $.ajax({
                        url: 'jsp/standard/resource/' + rightInterface,
                        method: 'POST',
                        dataType: 'text'
                    }).done(function (data) {
                        infoToTabForRightModule(data)
                    }).fail(function (err) {
                        $F.log("Load nav.json failed: " + err.statusText);
                    }).always(function () {
                        if (document.all) {
                            $("a[href='javascript:;']").on("click", function (e) {
                                e.preventDefault();
                            });
                        }
                    });
                }
            }
        }

        function infoToTabForRightModule(interfaceData) {
            //针对语右边栏的数据如果是 有轮播图片的需要 对轮播图片数据进行处理
            if (typeof interfaceData == "string") {
                interfaceData = JSON.parse(interfaceData);
            }
            if (interfaceData.margueeImg) {
                $F.loadingMargueeImg(interfaceData.margueeImg);
                delete interfaceData["margueeImg"];
            }

            if (typeof (setInfoToTabDivForRightModule) == 'function') {
                setInfoToTabDivForRightModule(interfaceData);
            }
        }

        $(window).resize(function () {
            tbResize();
        });
        $(window).resize();

        $("#sendBtn_div").on('click', function () {
            var content = chatEditor.html();
            $F.log("发送消息   " + content + ",   _transfering   " + _transfering)
            if (_transfering) {
                if (i18n.robot.hasTransferAgent)
                    $F.formatAndShowNotice(i18n.robot.hasTransferAgent, false);
                chatEditor.html("");
                return;
            }

            var c = content.replace(/\&nbsp;/g, "").replace(/<br \/>/g, "").replace(/\\/g, "\\").trim();
            if (c.length == 0) {
                chatEditor.html("");
                return;
            }
            content = content.replaceAll('<br />', '<br>').replaceAll('\r\n', '').replaceAll('\n\r', '').replaceAll('\r', '').replaceAll('\n', '').replaceAll('\b', ' ');
            while (content.endWith('<br>')) {
                content = content.substring(0, content.length - 4);
            }
            content = $ROBOT.orderNumToKey(content);
            if (Constants.robot.isRobot) {
                //isRobot is true cannot send message ,run into robot module
                //显示匹配是否是与队列的相匹配
                if (queueObj && queueObj.num && queueObj.use) {
                    //输入对应的数字进入相应的队列
                    if (parseInt(content) <= queueArr.length) {
                        createChat(queueArr[parseInt(content) - 1]);
                        UI.hideChangeModule();
                        $(this).parents('.queue').html('<em>' + i18n.page.queue.select.format('[' + $(this).text() + ']') + '</em>');
                        queueArr = [];
                    } else {
                        $F.log('[ robot no in queue ]');
                        doRobotSearch();
                    }
                } else {
                    $F.log('[ robot ]');
                    doRobotSearch();
                }
                chatEditor.html("");
                chatEditor.focus();
            } else {
                if (_sessionActive && $config.sessionId != -1) {
                    var num = i18n.page.maxWrite;
                    var lastNum = parseInt(num) - chatEditor.count("text");
                    if (lastNum < 0) {
                        alert(i18n.scripts.maxInputLengthExceeded);
                        return;
                    }
                    sendComment(content);
                }
            }
        });
    });

    /**
     * 生成随机的id
     * @returns {string}
     */
    function uuid() {
        var temp_url = URL.createObjectURL(new Blob());
        var uuid = temp_url.toString(); // blob:https://xxx.com/b250d159-e1b6-4a87-9002-885d90033be3
        URL.revokeObjectURL(temp_url);
        return uuid.substr(uuid.lastIndexOf("/") + 1);
    }

    sendCommentWithSearchKey = function (content, searchKey, fromType) {
        preMsg = content;
        if ($P.isValuesData(content)) {
            chatEditor.html("");
            chatEditor.focus();
        } else {
            var sendContent = content;
            if (sendContent.length > 0 && sendContent != "\\") {
                sendContent = sendContent.replace(/<a/gi, '<a target="_blank" ');
                //客户端显示消息
                displayMessage = sendContent.replaceAll('<br\/>', "").replaceAll("qqemoji", "");
                var messageId = uuid();
                displayMessage = $F.getDisplayMessage($config.client.clientId, $F.encodeStringByHTMLEscape($config.clientName), displayMessage, null, null, messageId);
                $F.appendTextToDiv("clientResponseDiv", displayMessage);
                //处理消息发送到坐席
                var $sendContent = $("<div>").append(sendContent);
                $sendContent.find('img.qqemoji').each(function (i, item) {
                    var emojiText = $EMOTION.QQ_EMOTION[$(item).attr('alt')];
                    sendContent = sendContent.replace(/<img ([^>]*) alt=\"([0-9]*)\"([^<]*)\/>/g, '[$2]');
                    sendContent = sendContent.replace('[' + $(item).attr("alt") + ']', '[' + emojiText + ']');
                });
                sendContent = sendContent.replace(/\\/g, '\\\\').replace(/\"/g, '\\"').replace(/\r\n/g, '').replace(/\n\r/g, '').replace(/\r/g, '').replace(/\n/g, '').replace(/\b/g, '').replace(/\\/g, '\\');
                if (sendContent.endWith("<br />"))
                    sendContent = sendContent.substring(0, sendContent.length - 6);
                if (sendContent.endWith("<br/>"))
                    sendContent = sendContent.substring(0, sendContent.length - 5);
                $F.doAjaxCall(Constants.ajaxURL, "requestType=send&data=" + $F.getPostMessageSentInfoJSONWithSearchKey(encodeURIComponent(sendContent), encodeURIComponent(searchKey), '', fromType), function (data) {
                    if (data.status == 'success') {
                        var sendResponse = data.sendResponse;
                        var newMessages = sendResponse.messages;
                        for (i in newMessages) {
                            var newMessage = newMessages[i];
                            var messageId = newMessage.id;
                            var text = newMessage.message;
                            if (text) {
                                $F.appendTextToDiv("clientResponseDiv", getMessageText(messageId, newMessage.userName, text, newMessage.userId, newMessage.messageType, newMessage.postTime, "", false));
                                setTimeout(blinkTitle(true), 1000);
                            }
                        }
                    }
                }, function () {
                    $('#' + messageId).addClass("send-fail").show();
                    //添加点击一次的事件
                    $('#' + messageId).one("click", function () {
                        $(this).removeClass('hide');
                        var content = $(this).parent().find('.content').html(), parant = $(this).parent();
                        setTimeout(function () {
                            parant.remove();
                        }, 500);
                        sendComment(content, "input");
                    })
                });
                chatEditor.html("");
                chatEditor.focus();
            }
        }
    }

    sendComment = function (content) {
        sendCommentWithSearchKey(content, "");
    }

    var showRating = function () {
        if ($ROBOT.notAllowShowRate(Constants.agent.id)) return;
        UI.initRate();
        sendRating();
    };

    var sendRating = function () {
        if (_firstShowRating) {
            var judge_div = $("#judge_pj_rg");
            var hei = $("html").height();
            var wid = $("html").width();
            var mheight = (hei - judge_div.height()) / 2;
            var mwidth = (wid - judge_div.width()) / 2;

            $("#judge_pj_rg").css({
                "position": "absolute",
                "left": mwidth,
                "top": mheight,
                "display": "block",
                "z-index": "300"
            });
            _firstShowRating = false;
            $(".bg_cover").show();
        } else {
            $(".bg_cover, #judge_pj_rg").show();
        }
    };

    function countWords(len, words) {
        var w = $("#" + words);
        var i = w.find("i");
        var num = i18n.page.maxWrite;
        var lastNum = parseInt(num) - len;
        if (lastNum < 10) {
            i.addClass("red");
        } else {
            i.removeClass("red");
        }
        if (lastNum < 0) {
            i.html("0");
            return false;
        } else {
            i.html(lastNum);
            return true;
        }
    }

    function initRateShowInterval() {
        //添加定时去显示满意度的
        if (parseInt($config.queue.rateIntervalShow)) {
            _showRatingTimer = setInterval(function () {
                judgeShowRate(Constants.rate.rateType.INTERVAL_SEND)
            }, parseInt($config.queue.rateIntervalShow) * 1000);
        }
    }

    function initJavaScript() {
        if ($config.queue.endUrl) {
            endUrl = $config.queue.endUrl;
            if (typeof endUrl == 'object') {
                if (_from && endUrl.hasOwnProperty(_from)) {
                    endUrl = endUrl[_from];
                }
            }
        }
        UI.loadResource();
        //加载轨迹
        if (_trackData) {
            $F.appendTextToDiv("clientResponseDiv", $ROBOT.parseFormattedMsg(_trackData));
        }
        $('.close').hide();
        config.common.rateTimes = 0;
        $("#clientMessageBox").attr("autocomplete", "off");
        $config.clientName = $config.client.clientFirstName + " " + $config.client.clientLastName;
        _timeoutForPull = $config.timeoutForPull;
        _checkAFKTimeout = $config.afkTimeout;
        $("#clientMessageBox").attr("disabled", false);

        if (Constants.robot.robotFirst) {
            UI.robot();
        } else {
            if (_autoStartChat) {
                createChat($config.queueId);
                UI.cuestomerService();
            }
        }

        $(window).blur(function () {
            _windowInFocus = false;
        });
        $(window).focus(function () {
            _windowInFocus = true;
        });

        $("#clientMessageBox").focus(function () {
            _clientMessageBoxInFocus = true;
        });
        $("#clientMessageBox").blur(function () {
            _clientMessageBoxInFocus = false;
        });
        $F.log($config.client.clientId + " userAgent: " + navigator.userAgent, true);

        $(".manual").on("click", function () {
            //如果机器人是中兴的机器人就需要去执行登陆的功能
            if ($ROBOT.isPocVersion()) {
                $("#popDiv").show();
            } else {
                loginWhenVisit(function () {
                    //显示对话框
                    $ROBOT.transferDialog("", function () {
                        $ROBOT.transferChat($config.queueId);
                        UI.cuestomerService();
                    })
                });
            }
        })

        $('.robot-client-dialog').on("click", function () {
            $('#popDiv').hide();
            $ROBOT.transferChat($config.queueId);
            UI.cuestomerService();
        })
        //初始化满意度
        if (typeof order != 'undefined' && order == 'DESC')
            ratings.reverse();
        $("#rating_img").attr("src", $config.baseUrl + "/img/61514403497625828.jpg");
        var htmlRate = '';
        $.each(ratings, function (i, rating) {
            htmlRate += '<li class="rate rate' + rating.ratingWeight + '" data-id="' + i + '">' +
                '<i class="rateImg rateImg' + rating.ratingWeight + '"></i>' +
                '<span>' + rating.ratingDescription + '</span>' +
                '<i class="checkImg checkImg' + rating.ratingWeight + '"></i>' +
                '</li>';
        })
        $('.re_radio').html(htmlRate);
        if (ratings.length == 1) {
            $('.re_radio').hide();
        }
        $('.rate',"#judge_pj_rg").on('click', function () {
            var checkId = $(this).data('id');
            $('.checked', "#judge_pj_rg").removeClass('checked');
            $(this).addClass("checked", true);
            showClickRate(checkId);
        });

        //满意度提交
        $("#ratingSubmit").click(function () {
            var self = $(this);
            self.hide();
            setTimeout(function () {
                self.show();
            }, 1000);
            var ratingExtendContent = [];
            var checkId = $('.checked', '#judge_pj_rg').data('id') || 0;
            var rating = ratings[parseInt(checkId)];
            var rateid = rating.ratingId;
            if (rating && rating.needComment == 1 && rating.contentFlag) {
                var contentFlag = rating.contentFlag
                if (contentFlag == 1) {
                    var ratingComments = $("#pjwords").val();
                    if (!ratingComments) {
                        var tag = i18n.common.ratePageContent.contentFlagTag;
                        if (rating.contentFlagTag) {
                            tag = rating.contentFlagTag;
                        }
                        alert(tag);
                        return;
                    }
                }
            }
            var starWeightHasUndefind = false;
            if (rating.ratingExtendFlag == 1) {
                var ratingExtends = rating.ratingExtends, ratingExtendFoldFlag = false;
                $.each(ratingExtends, function (i, ratingExtend) {
                    if (ratingExtend.type == RateExtendType.FOLD) {//获取到值之后去判断数据是不是对的，如果类型是F，并且data-required = 1 并且孩子是checkbox的时候就去判断至少选择一个
                        if (ratingExtend.requiredType == 1) {
                            var flagFequiredForFold = false;
                            $.each(ratingExtends, function (i, ratingExtendFold) {
                                if (ratingExtendFold.parentId == ratingExtend.id && ratingExtendFold.type == RateExtendType.CHECKBOX) {
                                    if ($('input[name="checkBox' + ratingExtendFold.id + '"]').is(':checked')) {
                                        flagFequiredForFold = true;
                                        return false;
                                    }
                                }
                            })
                            if (!flagFequiredForFold) { //false 说明没有选中的需要添加提示
                                alert(i18n.common.typeIsFoldInRateNoneSelectAlert.format(ratingExtend.description));
                                ratingExtendFoldFlag = true;
                                return false;
                            }
                        }
                        //获取对应的radio内容的数据就不存在
                        var radioData = $("input[name='" + ratingExtend.id + "']:checked", "#judge_pj_rg").val();
                        if (radioData) {
                            ratingExtendContent.push($F.getRatingExtendInfoJSON(rateid, ratingExtend.id, RateExtendType.RADIO, radioData));
                        }
                    }
                    if (ratingExtend.type == RateExtendType.CHECKBOX) {
                        if ($('input[name="checkBox' + ratingExtend.id + '"]', "#judge_pj_rg").is(':checked')) {
                            ratingExtendContent.push($F.getRatingExtendInfoJSON(rateid, ratingExtend.id, ratingExtend.type, 1));
                        }
                    } else if (ratingExtend.type == RateExtendType.INPUT) {
                        ratingExtendContent.push($F.getRatingExtendInfoJSON(rateid, ratingExtend.id, ratingExtend.type, $('.reason-input' + ratingExtend.id + '').val()));
                    } else if (ratingExtend.type == RateExtendType.STAR) {
                        //当前是start的界面的时候要判断是否是选择了评价  没有就提示
                        var $starDom = $('.reason-box' + ratingExtend.id + ' .active').last(),
                            startWeight = $starDom.data("weight"), needComment = $starDom.data("need"),
                            textareaClass = $starDom.data("textarea");
                        $F.log("star 满意度选择的内容[" + startWeight + "]");
                        if (typeof startWeight == 'undefined') {
                            starWeightHasUndefind = true;
                        }
                        if (needComment == 1) {
                            var dataComment = $("textarea", textareaClass).last().val();
                            if (dataComment) {
                                ratingExtendContent.push($F.getRatingExtendInfoJSON(rateid, ratingExtend.id, "C", dataComment));
                            }
                        }
                        ratingExtendContent.push($F.getRatingExtendInfoJSON(rateid, ratingExtend.id, ratingExtend.type, startWeight));
                    }
                });
                if (ratingExtendFoldFlag) {
                    return;
                }
            }

            if (starWeightHasUndefind) {
                alert(i18n.common.rateStarAlert);
                return;
            }

            $.ajax({
                method: "post",
                url: Constants.ajaxURL,
                data: {
                    requestType: "rateSession",
                    data: $F.getSessionRatingJSON(rateid, $("#pjwords").val(), ratingExtendContent)
                }
            }).done(function () {
                updateRateTimes(Constants.rate.rateSender);
                $("#pjwords").val("");
                $(".bg_cover, #judge_pj_rg").hide();
                var promptTag = rating.promptTag;  //满意度显示样式
                // $F.formatAndShowNotice(rating.promptTag);
                appendRateResult(promptTag);
            }).fail(function () {
                alert(i18n.page.ratingFailed);
            }).always(function () {
                $F.rateAfter();
            });
        });

        function appendRateResult(promptTag) {
            var parentDom = "#judge_pj_rg";
            var inputs = $('.reason-input', parentDom);
            var checkedBoxes = $("input[type='checkbox']", parentDom);
            var doms = '<form class="chat-rate chat-rate-now rate-result clear_box pop-main">' +
                '<div class="chat-comment pop-judge">' +
                '<div class="pop-main">' +
                '<ul class="re-ra re_radio">' + $(".re_radio", parentDom).html() + '</ul>' +
                $(".reason", parentDom)[0].outerHTML +
                '</div>';
            var $rateComments = $(".suggest_textarea", parentDom), $rateCommentLast = $rateComments.last(),
                commentVal = $("#pjwords", $rateCommentLast).val();
            if (commentVal) {
                doms += $(".suggest_textarea", parentDom).last()[0].outerHTML;
            }
            if (promptTag) {
                doms += '<div style="text-align: center">' +
                    '<span class="title">' + promptTag + '</span>' +
                    '</div>';
            }
            doms += '</div></form>';
            var clientName = (Constants.client.clientFirstName || i18n.page.visitClientName);
            if ($config.client.clientType == 1) {
                clientName = i18n.page.visitClientName || clientName;
            }
            doms = '<div class="message clearfix me">' +
                '<div class="nowtime me-time"><span class="me-name">' + clientName + '</span>' +
                '<span>' + $F.getLocalTime() + '</span>' +
                '</div>' +
                '<div class="avatar"><img src="' + Constants.client.iconUrl + '" alt="' + Constants.client.iconAlt + '" /><i class="icon"></i></div>' +
                '<div class="content">' + doms + '</div>' +
                '</div>';
            $('#clientResponseDiv').append(doms);
            $.each(inputs, function () {
                var $input = $(this);
                var inputClass = '.' + $input[0].className.split(' ')[1];
                $(inputClass, '.chat-rate-now').val($(inputClass, parentDom).val()).prop("disabled", "disabled");
            })
            $.each(checkedBoxes, function (j, checkedBox) {
                console.log("checked : " + $(checkedBox).prop("class") && $(checkedBox).is(':checked') + ", value : " + $(checkedBox).val())
                if ($(checkedBox, "#judge_pj_rg").prop("class")) {
                    $(checkedBox, '.chat-rate-now').removeAttr("checked");
                    $('.' + $(checkedBox).prop("class"), '.chat-rate-now')
                        .prop("checked",$(checkedBox).is(':checked'));
                }
            })
            $('.chat-rate').removeClass('chat-rate-now');
            $('.chat-rate .suggest_textarea p').empty();
            $.each($rateComments, function (i, rateComment) {
                $("textarea", ".rate-result .suggest_textarea").eq(i).val($("textarea", rateComment).val()).prop("disabled", "disabled");
            })

            $(".chat-rate").removeClass("rate-result");
            $.each($("input", '.chat-rate'), function () {
                $(this).prop("disabled", "disabled");
            })
            $.each($("textarea", '.chat-rate'), function () {
                $(this).prop("disabled", "disabled");
            })
            $("#talkBox")[0].scrollTop = $("#talkBox")[0].scrollHeight + 30;
        }

        //满意度取消
        $("#ratingCancel").on("click", function () {
            $(".bg_cover, #judge_pj_rg").hide();
            UI.initRate();
        });

        //注册聊天历史点击事件
        $(".hischat").on("click", function () {
            _showHistoryChating = true;
            // _fromMessageId = 0;
            if (firstClickHis) {
                $(".his-body").html("");
                firstClickHis = false;
            }

            $(".his_box").show();
            //加载聊天历史
            if (_firstShowHis) {
                _firstShowHis = false;
                showHistory(function (time, html, id) {
                    if (html) {
                        var target;
                        try {
                            target = $(html);
                        } catch (e) {
                        }
                        if (!target || target.length == 0) {
                            target = $('<div>' + html + '</div>');
                        }
                        $F.parseMessageFromContainer(target, $(".his-body"));
                        $(".his-body").prepend(target);
                        $F.messageFromContainer();
                    }
                }, function (message) {
                    $(".hischat").hide();
                })
            }
        })

        //注册聊天历史点击事件
        $(".button-load").on("click", function () {
            _showHistoryChating = true;
            //加载聊天历史
            showHistory(function (time, html) {
                if (html) {
                    var target;
                    try {
                        target = $(html);
                    } catch (e) {
                    }
                    if (!target || target.length == 0) {
                        target = $('<div>' + html + '</div>');
                    }
                    $F.parseMessageFromContainer(target, $(".his-body"));
                    $(".his-body").prepend(target);
                    $F.messageFromContainer();
                }
            })
        })
        $(".button-load-talk").on("click", function () {
            _showHistoryChating = true;
            //加载聊天历史
            showHistory(function (time, html) {
                if (html) {
                    $F.prependTextToDiv("clientResponseDiv", html);
                }
            }, function (message) {
                $(".button-load-talk").hide();
            })
        })

        //隐藏聊天历史的弹框
        $(".closeHis").on("click", function () {
            _showHistoryChating = false;
            $(".his_box").hide();
        })

        //创建聊天消息历史和输入框的上下splitter 20210928先隐藏掉吧，等修改了输入框不用插件了再看看效果
        // $('.chat-container').wisSplitter({
        //     direct : 'v',
        //     cookie : 'chat.contentSplitter',
        //     minSize: 180,
        //     maxSize: 400,
        //     fixedSize: 200,
        //     fixed: 1,
        //     endMove: function () {
        //         tbResize();
        //     }
        // });
    }

    function getMessageText(messageId, userName, texts, userId, messageType, posttime, icon, flag) {
        messageMap[messageId] = 1;
        var container = '';
        if (texts) {
            texts = $ROBOT.getRobotText(texts, userId, flag, messageId);
            if (typeof texts == 'object' && $.isArray(texts)) {
                $.each(texts, function (i, text) {
                    if (text) {
                        container += $F.getDisplayMessage(userId, userName, {
                            id: messageId,
                            messageType: messageType,
                            text: text
                        }, posttime, icon)
                    }
                })
            } else {
                if (texts) {
                    container += $F.getDisplayMessage(userId, userName, {
                        id: messageId,
                        messageType: messageType,
                        text: texts
                    }, posttime, icon);
                }
            }
        }
        return container;
    }

    function showContinueMessage(messages) {
        var container = "";
        try {
            $.each(messages, function (i, msg) {
                if (msg.revokeFlag != 1) {
                    $ROBOT.setMaxHisMessageId(msg.id);
                    container += getMessageText(msg.id, msg.userName, msg.message, msg.userId, msg.messageType, msg.postTime, msg.icon, true);
                }
            });
        } catch (e) {
        }
        if (container) {
            $F.appendTextToDiv("clientResponseDiv", container);
        }
    }

    function processSendReturn(response, transferFlag) {
        if (!transferFlag)
            transferFlag = false;
        else {
            if (_pullTimer) {
                clearTimeout(_pullTimer);
            }
        }
        $F.log("Response from send : " + JSON.stringify(response));
        var jsonResponse = response;
        if (jsonResponse.status === "success") {
            var receivedInfo = jsonResponse.sendResponse;
            var orderInQueue = receivedInfo.orderInQueue;
            var result = receivedInfo.result;
            if (result === 1) {//success
                _lastRequestId = receivedInfo.chatRequestId;
                _chatRequestId = receivedInfo.chatRequestId;
                var userType = receivedInfo.userType;
                var continueLastSession = receivedInfo.continueLastSession;
                if (continueLastSession) { //继续之前的聊天
                    $config.sessionId = receivedInfo.sessionId;
                    $config.thisSessionId = $config.sessionId;
                    var messages = receivedInfo.messages; //当前会话的历史
                    var usersInSession = receivedInfo.usersInSession;
                    var agent = usersInSession[0];
                    if (agent) {
                        setAgentInfo(agent);
                        if ($ROBOT.isRobot(agent.id)) {
                            UI.loadHotTop(); //加载热点知识
                            loadBusinessKeys();
                            //继续之前的聊天，坐席是机器人的时候，判断transfer 属性如果是true那么直接转人工
                            if ($config.transfer) {
                                var robotId = agent.id;
                                if (robotId == 'BOT008') {
                                    var cookies = document.cookie;
                                    if (cookies.length > 0) {
                                        var cookieArr = cookies.split(";");
                                        var UCSSSOAccount = "";
                                        $.each(cookieArr, function (i, cookie) {
                                            var param = cookie.trim().split('=');
                                            if (param[0] == 'UCSSSOAccount') {
                                                UCSSSOAccount = param[1];
                                            }
                                        });

                                        //判断token 如果没有就去认证
                                        if (UCSSSOAccount !== '') {
                                            //调用接口判断权限
                                            checkRoleManager(UCSSSOAccount, function () {
                                                $ROBOT.transferChat($config.queueId);
                                            })
                                        }
                                    }
                                } else {
                                    $ROBOT.transferChat($config.queueId);
                                }
                            }
                            UI.robot();
                        } else {
                            initRateShowInterval();
                            UI.cuestomerService();
                            UI.chatTool();
                        }
                    }
                    showContinueMessage(messages);
                    $config.sessionId = receivedInfo.sessionId;
                    $config.thisSessionId = $config.sessionId;
                    _chatRequestId = -1;
                    if (receivedInfo.feedbackMessage)
                        $F.formatAndShowNotice(receivedInfo.feedbackMessage);
                    focusClientMessageBox();
                    chatEditor.readonly(false);
                    $("#sen_div").show();
                    $("#close_div").show();
                    _pullTimer = setTimeout(pullFromServer, _timeoutForPull);
                    setInterval(checkForPull, 10000);
                    $(window).resize();
                } else if (userType == 12) {
                    var usersInSession = receivedInfo.usersInSession;
                    var agent = usersInSession[0];
                    setAgentInfo(agent);
                    $config.sessionId = receivedInfo.sessionId;
                    $config.thisSessionId = $config.sessionId;
                    _chatRequestId = -1;
                    //如果参数里带有transfer 的字段的时候 就需要直接自动转人工请求
                    if ($config.transfer && $ROBOT.isRobot(agent.id)) {
                        $ROBOT.transferChat($config.queueId);
                    } else {
                        UI.loadChatTime($config.queue);
                        UI.robot();
                        timer = setInterval(function () {
                            $config.chatTime++;
                            config.common.clientTimeInit++;
                            if (parseInt($config.chatTime / 60) > 0) {
                                $("#time").html(parseInt($config.chatTime / 60) + i18n.common.minutes + $config.chatTime % 60 + i18n.common.seconds)
                            } else {
                                $("#time").html($config.chatTime % 60 + i18n.common.seconds)
                            }
                        }, 1000);
                        UI.loadHotTop(); //加载热点知识
                        loadBusinessKeys();
                        var feedbackMessage = i18n.page.RobotAcceptTip;
                        if (receivedInfo.feedbackMessage) {
                            feedbackMessage = receivedInfo.feedbackMessage;
                        }
                        if (feedbackMessage) {
                            $F.formatAndShowNotice(feedbackMessage);
                        }
                        var robotEngineConfig = $config.robotEngineConfig;
                        if (typeof robotEngineConfig == 'string') {
                            robotEngineConfig = JSON.parse(robotEngineConfig);
                        }

                        var welcomeMessage = robotEngineConfig.welcomeMessage;
                        if (welcomeMessage) {
                            var zrgRegExp = new RegExp(/\[ZRG](.*?)\[\/ZRG]/g);
                            if (zrgRegExp.test(welcomeMessage)) {
                                welcomeMessage = welcomeMessage.replace(zrgRegExp, '<a class="transfer-notice">$1</a>');
                                welcomeMessage = '<div class="message message-notice session-round" data-click="true">' +
                                    '<div class="transfer-notices">' + welcomeMessage + '</div>' +
                                    '</div>';
                            }
                            if (robotEngineConfig && !$F.isEmpty(robotEngineConfig.welcomeMessageType)) {
                                var welcomeMessageType = robotEngineConfig.welcomeMessageType;
                                if (welcomeMessageType == 0) {
                                    $F.formatAndShowNotice(welcomeMessage);
                                } else if (welcomeMessageType == 1) {
                                    var displayMsg = $F.getDisplayMessage(Constants.agent.id, robotEngineConfig.name, welcomeMessage);
                                    $F.appendTextToDiv("clientResponseDiv", displayMsg);
                                }
                            }
							$(".button-load-talk").show();
							$(".button-load-talk").click();
                        }
                        focusClientMessageBox();
                        chatEditor.readonly(false);
                    }

                    $("#sen_div").show();
                    $("#close_div").show();
                    _pullTimer = setTimeout(pullFromServer, _timeoutForPull);
                    setInterval(checkForPull, 10000);
                } else {
                    _pullTimer = setTimeout(pullFromServer, _timeoutForPull);
                    setInterval(checkForPull, 10000);
                }
                if (receivedInfo.waitTimeMessage)
                    showChatView(orderInQueue, receivedInfo.waitTimeMessage);
            } else {
                if (result == -3) { //NOT_IN_WORKTIME
                    $F.formatAndShowNotice((receivedInfo.feedbackMessage || $config.notInWorkTimeMessage) + $F.openATag(config.common.openLinkType, Constants.lm.hrefUrl, Constants.lm.name, "", ""));
                    if (!transferFlag) _sessionActive = false;
                    else {
                        _chatRequestId = -1;
                        if ($ROBOT.hasRobot())
                            UI.robot()
                    }
                } else if (result == -24) { //MAX_QUEUED_REQUESTS_REACHED
                    $F.formatAndShowNotice((receivedInfo.feedbackMessage || $config.allAgentBusyMessage) + $F.openATag(config.common.openLinkType, Constants.lm.hrefUrl, Constants.lm.name, "", ""), true, Constants.formatNoticeType.OUTTIME);
                    if (!transferFlag) _sessionActive = false;
                    else {
                        _chatRequestId = -1;
                        if ($ROBOT.hasRobot())
                            UI.robot()
                    }
                } else if (result == Constants.RequestStatus.DIFFERENT_SESSION_TYPE) {
                    if (receivedInfo.feedbackMessage) {
                        $F.formatAndShowNotice(receivedInfo.feedbackMessage);
                    } else {
                        $F.formatAndShowNotice(i18n.page.loginOnOtherDevice);
                    }
                    if (!transferFlag) _sessionActive = false;
                    else {
                        _chatRequestId = -1;
                        if ($ROBOT.hasRobot())
                            UI.robot()
                    }
                } else {
                    if (!transferFlag) {
                        _sessionActive = false;
                        chatEditor.readonly(true);
                    }
                    if (orderInQueue == -1) {
                        $config.hasCreateChat = false;
                        $F.formatAndShowNotice((receivedInfo.feedbackMessage || $config.noAgentOnlineMessage) + $F.openATag(config.common.openLinkType, Constants.lm.hrefUrl, Constants.lm.name, "", ""), false, Constants.formatNoticeType.OUTTIME);
                    } else if (orderInQueue == -2) {
                        $config.hasCreateChat = false;
                        $F.formatAndShowNotice((receivedInfo.feedbackMessage || $config.notInWorkTimeMessage) + $F.openATag(config.common.openLinkType, Constants.lm.hrefUrl, Constants.lm.name, "", ""));
                    }
                    _sessionActive = true;
                    _pullTimer = setTimeout(pullFromServer, _timeoutForPull);
                    setInterval(checkForPull, 10000);
                }
            }
        }
    }

    /**
     * 更新时间 坐席接受客户请求的时候使用
     * @param Y
     */
    function updateClock(Y) {
        Y = Y + 1;
        var C = Y % 60;
        var x = Math.floor(Y / 60);
        if (document.getElementById("secondsBlock") != null) {
            if (C == 0) {
                document.getElementById("secondsBlock").innerHTML = "";
            }
            var r = "&nbsp;";
            r = r + document.getElementById("secondsBlock").innerHTML;
            document.getElementById("secondsBlock").innerHTML = r;
            document.getElementById("secondsLabel").innerHTML = C;
            if (x > 0) {
                if (document.getElementById("minBarDiv").style.display == "none") {
                    document.getElementById("minBarDiv").style.display = "block";
                }
                r = "";
                for (var j = 0; j < x; j++) {
                    r = r + "&nbsp;";
                }
                document.getElementById("minutesBlock").innerHTML = r;
                document.getElementById("minutesLabel").innerHTML = x;
            }
            if (_clockTimer)
                clearTimeout(_clockTimer);
            _clockTimer = setTimeout(function () {
                updateClock(Y);
            }, 1000);
        }
    }

    function showChatView(orderInQueue, message) {
        $F.log(" orderInQueue " + orderInQueue + " message " + message);
        if (orderInQueue >= 0) {
            if (message && typeof message == 'string' && message.startWith("{")) {
                message = JSON.parse(message);
            }
            if ($config.queue.skin == 'thin') {
                var html = "<div class='message'> <div class=\"loadmsg inqueue-load\"><h2>" + i18n.page.inqueueTaps + "</h2>" +
                    "<br><p>" + message.requestRoutedMessage + "</p><br><p>" + message.positionInQueueMessage + "</p></div>";
                if (Constants.lm.url) {
                    html = html + $F.openATag(config.common.openLinkType, Constants.lm.hrefUrl, Constants.lm.name, "", "");
                }
                html += "</div>";
                $F.formatAndShowNotice(html, false, Constants.formatNoticeType.QUEUE);
            } else {
                if ($config.queue && $config.queue.queueClock) {
                    if (message) {
                        var html = '<div class="message">' +
                            '<div id="minBarDiv" class="inqueue-load" style="display:none;">'
                            + message.minutes + ':<div class="progress-minute"><span id="minutesBlock"></span>' +
                            '</div><span ID="minutesLabel"></span>' +
                            '<br><br></div><div>'
                            + message.seconds + ':<div class="progress_seconds"><span id="secondsBlock"></span></div><span id="secondsLabel"></span>' +
                            '<br><br>' + message.requestRoutedMessage +
                            '<br><br>' + message.positionInQueueMessage +
                            '<br>' + message.canelRequestMessagePrefix;
                        // if (Constants.lm.url) {
                        //     html += html + $F.openATag(config.common.openLinkType, Constants.lm.hrefUrl, Constants.lm.name, "", "");
                        // }
                        html += '<a class="queue-cancel" href="javascript:void(0);" onclick="$F.giveUpChat(' + message.chatRequestId + ')" alt="Cancel">' + message.canelRequestMessagePostfix + '</a>';
                        html += "</div></div>";
                        $F.formatAndShowNotice(html, false, Constants.formatNoticeType.QUEUE);
                        updateClock(0);
                    }
                } else {
                    var html = "<div class='message'> <div class=\"loadmsg inqueue-load\"><h2>" + i18n.page.inqueueTaps + "</h2>" +
                        "<br>" + message.requestRoutedMessage + "<br>" + message.positionInQueueMessage;
                    html += '<a class="queue-cancel" href="javascript:void(0);" onclick="$F.giveUpChat(' + message.chatRequestId + ')" alt="Cancel">' + message.canelRequestMessagePostfix + '</a>';
                    html += "</div>";
                    if (Constants.lm.url) {
                        html = html + $F.openATag(config.common.openLinkType, Constants.lm.hrefUrl, Constants.lm.name, "", "");
                    }
                    html += "</div>";
                    $F.formatAndShowNotice(html, false, Constants.formatNoticeType.QUEUE);
                }

            }
        }
        // else if (orderInQueue > 0) {
        //     var currentPositionInQueueMessage = $config.currentPositionInQueueMessage;
        //     currentPositionInQueueMessage = currentPositionInQueueMessage.replace(/\{0\}/g, '<span id=\'orderInQueue\'>" + orderInQueue + "</span>');
        //     $("#waitingForAcceptInChatView").html(formatTopNotice(currentPositionInQueueMessage + ',点击<a href="###" onclick="$F.giveUpChat()">这里</a>放弃排队'));
        // }

    }

    function pullFromServer() {
        if (_sessionActive) {
            _lastPullTime = new Date().getTime();
            var pullRequest = $F.doAjaxCall(Constants.ajaxURL, {
                requestType: 'pull',
                data: getPullSendInfoJSON()
            }, callbackForPull, function (xhr, status) {
                if (status === 'timeout') {
                    $F.log('Pull request timeout', true);
                    pullRequest.abort();
                    _pullTimer = setTimeout(pullFromServer, _timeoutForPull);
                }
            }, 15 * 1000, {
                loggedInTime: $config.loggedInTime
            });
        }
    }

    function getPullSendInfoJSON() {
        var pullSendInfoJSON = {
            senderId: $config.client.clientId
        };
        if (_chatRequestId != -1) {
            var chatRequestIds = [_chatRequestId];
            pullSendInfoJSON.chatRequestIdsFromUser = chatRequestIds;
        }
        if ($config.sessionId != -1) {
            var sessionIds = [$config.sessionId];
            pullSendInfoJSON.sessionIds = sessionIds;
        }
        return JSON.stringify(pullSendInfoJSON);
    }

    function callbackForPull(data) {
        if (!data) {
            alert(i18n.page.ajax.noRespose);
        } else {
            if (data === "retry") {
                _retryTimes = _retryTimes + 1;
                if (_retryTimes > _maxRetry) {
                    alert(i18n.page.ajax.resposeError);
                }
            } else {
                _retryTimes = 0;
                processPullReturn(data);
            }
        }
        if (_sessionActive) {
            _pullTimer = setTimeout(pullFromServer, _timeoutForPull);
        } else {
            $F.log("Stop pullFromServer for session " + $config.thisSessionId + " hence sessionActive is " + _sessionActive, true);
        }
    }

    /**
     * 显示通知信息 ，对客户资料进行调查更新
     */
    function showNoticeForAgent() {
        $.ajax({
            url: 'jsp/standard/resource/supplyInformation.json',
            data: {
                'client_guid': $config.client.clientId,
                'queue': $config.queueId
            },
            method: 'POST',
            dataType: 'json'
        }).done(function (data) {
            var noticeProperty = [];
            if (data) {
                var noticeHtml = '';
                var url = data.url;
                data = data.data;
                $.each(data, function (j, noticeData) {
                    var queueArr = noticeData.queue;
                    if (queueArr.length == 0 || jQuery.inArray($config.queueId, queueArr) > -1) { //如果数组是 空的或者是 数组内包含当前的队列号
                        var noticeTitle = noticeData.title;
                        var content = noticeData.content;
                        noticeHtml = '<div class="notice-supply-info">';
                        noticeHtml += '<div class="notice-title">' +
                            '<span>' + noticeTitle + '</span>' +
                            '<i class="notice-close">' +
                            '</i>' +
                            '</div>';

                        $.each(content, function (i, nodeItem) {
                            noticeProperty.push({
                                "type": nodeItem.IOQType,
                                "property": nodeItem.property
                            })
                            if (nodeItem.IOQType == 'I') {
                                noticeHtml += '<label class="notice-box notice-box' + i + '">'
                                    + '<span>' + nodeItem.title + '</span>'
                                    + '<input type="text" class="notice-input notice-input' + i + '" name="' + nodeItem.property + '" placeholder="' + i18n.page.rate.inputPlaceholder + '" max="' + nodeItem.max + '"  min="' + nodeItem.min + '" />'
                                    + '</label>';
                            } else if (nodeItem.IOQType == 'O') {
                                noticeHtml += '<label class="notice-box notice-box ' + i + '"><span>' + nodeItem.title + '</span>';
                                var noticeForCheck = nodeItem.content;
                                $.each(noticeForCheck, function (m, checkData) {
                                    noticeHtml += '<li><label><input type="checkbox" value="' + checkData.val + '" name="' + nodeItem.property + '" /><i class="noticeExtendkImg noticeExtendImg' + m + '"></i><span>' + checkData.show + '</span></label><i class="notice-CheckImg notice-CheckImg' + m + '"></i></li>';
                                });
                                noticeHtml += '</label>';
                            } else if (nodeItem.IOQType == 'Q') {
                                noticeHtml += '<select name="select" class="type text-input ' + nodeItem.property + '">';
                                if (nodeItem.content) {
                                    $.each(nodeItem.content, function (n, item) {
                                        noticeHtml += '<option value="' + item.val + '">' + item.show + '</option>'
                                    })

                                }
                                noticeHtml += '</select>';
                            } else if (nodeItem.IOQType == 'R') {
                                noticeHtml += '<label class="notice-box notice-box ' + i + '"><span>' + nodeItem.title + '</span>';
                                var noticeForCheck = nodeItem.content;
                                $.each(noticeForCheck, function (r, checkData) {
                                    noticeHtml += '<li><label><input type="radio"  value="' + checkData.val + '" name="' + nodeItem.property + '" /><i class="noticeExtendkImg noticeExtendImg' + r + '"></i><span>' + checkData.show + '</span></label><i class="notice-CheckImg notice-CheckImg' + r + '"></i></li>';
                                })
                                noticeHtml += '</label>';
                            }
                        });
                        noticeHtml += '<label class="notice-box"> <button class="btn submit notice-submit">提交</button> </label></div>';
                    }
                })
                //生成html代码   并扩展到界面上
                if (noticeHtml) {
                    $(".show-notice").html(noticeHtml);
                    $(".show-notice").css("display", "block");
                    //添加点击事件 提交数据
                    $(".notice-close").on("click", function () {
                        $(".show-notice").html("");
                        $(".show-notice").css("display", "none");
                    });

                    $(".notice-submit").on("click", function () {
                        var noticeSubmitData = new Object();
                        noticeSubmitData.queue = $config.queueId;
                        noticeSubmitData.client_guid = $config.client.clientId;
                        $.each(noticeProperty, function (i, notice) {
                            if (notice.type == "I") {
                                noticeSubmitData[notice.property] = $(".notice-box > input[name='" + notice.property + "']").val()
                            } else if (notice.type == "O") {
                                var data = [];
                                $.each($(".notice-box input[name='" + notice.property + "']"), function (i, item) {
                                    data.push(item.value)
                                })
                                noticeSubmitData[notice.property] = data.join(",");
                            } else if (notice.type == "Q") {
                                noticeSubmitData[notice.property] = $("." + notice.property).val();
                            } else if (notice.type == "R") {
                                $.each($(".notice-box input[name='" + notice.property + "']"), function (i, item) {
                                    if (item.checked) {
                                        noticeSubmitData[notice.property] = item.value;
                                    }
                                })
                            }
                        });
                        //提交数据
                        $.ajax({
                            url: url,
                            data: noticeSubmitData,
                            method: 'POST',
                            dataType: 'json'
                        }).done(function (data) {
                            if (data.state == 1) {
                                alert(data.msg);
                            } else {
                                alert(data.msg);
                            }
                        }).always(function () {
                            $(".notice-close").click();
                        });
                    });
                }
            }
        }).always(function () {
        });
    }

    function processPullReturn(response) {
        $F.log('pull：' + JSON.stringify(response));
        var jsonResponse = response;
        if (jsonResponse.status == "success") {
            var receivedInfo = jsonResponse.pullResponse;
            var chatRequestsFromUser = receivedInfo.chatRequestsFromUser;
            if (chatRequestsFromUser != null && chatRequestsFromUser != "" && chatRequestsFromUser.length > 0) {
                var chatRequest = chatRequestsFromUser[0];
                var status = chatRequest.status;
                if (status == Constants.RequestStatus.ACCEPTED) {
                    //加载历史
                    if (typeof $config.queue.robotEngineConfig !== 'object') {
                        if ($config.queue.historyLoad == 1) {
                            setTimeout(function () {
                                if ($.inArray("hisTop", config.items) == -1) {
                                    $(".button-load-talk").click();
                                } else {
                                    $(".hischat").click();
                                }
                            }, 500);
                        }
                    }
                    $('.inqueue-notice').parent().remove();
                    $('.inqueue-load').parent().remove();
                    UI.displayNoneForInQueueNotice();
                    $ROBOT.transferingChange(false)
                    // _transfering = false;
                    clearTimeout(timer);
                    $ROBOT.robotOrderObj = {};
                    UI.loadChatTime($config.queue);
                    initRateShowInterval();
                    var agent = chatRequest.user;
                    setAgentInfo(agent);
                    UI.chatTool();
                    if (typeof (runFunctionForSelf) == 'function')
                        runFunctionForSelf();
                    var feedbackMessage = chatRequest.feedbackMessage;
                    timer = setInterval(function () {
                        $config.chatTime++;
                        config.common.clientTimeInit++;
                        if (parseInt($config.chatTime / 60) > 0) {
                            $("#time").html(parseInt($config.chatTime / 60) + i18n.common.minutes + $config.chatTime % 60 + i18n.common.seconds)
                        } else {
                            $("#time").html($config.chatTime % 60 + i18n.common.seconds)
                        }
                    }, 1000);
                    $config.sessionId = chatRequest.sessionId;
                    $config.thisSessionId = $config.sessionId;
                    $F.doAjaxCall(Constants.ajaxURL, {
                        requestType: 'setCurrentChatSessionId',
                        sessionId: $config.sessionId
                    });
                    _chatRequestId = -1;
                    //$("#waitingForAcceptInChatView").hide();
                    if ($config.queue.welcomeMessage)
                        $F.formatAndShowNotice($config.queue.welcomeMessage);
                    $F.formatAndShowNotice(feedbackMessage, true);
                    focusClientMessageBox();

                    $("#clientMessageBox").keyup(function () {
                        if (_sessionActive) {
                            var msg = $("#clientMessageBox").html();
                            $F.doAjaxCall(Constants.ajaxURL, {
                                requestType: 'send',
                                data: $F.getPostMessageSentInfoJSON(encodeURIComponent($F.encodeStringForHtmlEditor($F.convertEnterToBr(msg))), "postTempMessage")
                            });
                        }
                    });
                    chatEditor.readonly(false);
                    $("#sen_div").show();
                    $("#close_div").show();

                } else {
                    if (status == Constants.RequestStatus.UPDATENUMINQUEUE) {
                        var feedbackMessage = chatRequest.feedbackMessage;
                        var orderInQueue = $("#orderInQueue");
                        var queueTips = $F.openATag(config.common.openLinkType, Constants.lm.hrefUrl, Constants.lm.name, "", "");
                        queueTips += $config.currentPositionInQueueMessage;
                        if (orderInQueue && orderInQueue[0]) {
                            orderInQueue.html(feedbackMessage);
                        } else {
                            var tips = "<div class='message'>" +
                                "<div class=\"no-bg no-yel inqueue-notice\">" +
                                "<div class=\"notice\">" +
                                queueTips.replace("{0}", "<div id=\"orderInQueue\" style=\"display: inline-block\">" + feedbackMessage + "</div>") +
                                (i18n.page.cancelInQueue ? '<a class="queue-cancel" href="javascript:void(0);" onclick="$F.giveUpChat(' + _chatRequestId + ')" alt="Cancel">' + i18n.page.cancelInQueue + '</a>' : "") +
                                "</div>" +
                                "</div>" +
                                "</div>";
                            $F.formatAndShowNotice(tips, false, Constants.formatNoticeType.QUEUE);
                        }
                    } else {
                        if (status == Constants.RequestStatus.TIMEOUT) {
                            var timeoutTips = $config.allAgentBusyMessage;
                            if (Constants.lm.url) {
                                timeoutTips += $F.openATag(config.common.openLinkType, Constants.lm.hrefUrl, Constants.lm.name, "", "");
                            }
                            var timeout = $("#timeOut");
                            if (timeout[0]) {
                                timeout.html(timeoutTips);
                            } else {
                                var transferNotice = $(".transferNotice");
                                if (!transferNotice[0]) {
                                    $F.formatAndShowNotice(timeoutTips, false, Constants.formatNoticeType.OUTTIME);
                                }
                            }
                        } else if (status == Constants.RequestStatus.BLOCKED) {
                            if (receivedInfo.feedbackMessage) {
                                $F.formatAndShowNotice(receivedInfo.feedbackMessage);
                            } else {
                                $F.formatAndShowNotice($config.allAgentBusyMessage + $F.openATag(config.common.openLinkType, Constants.lm.hrefUrl, Constants.lm.name, "", "")
                                    , false, Constants.formatNoticeType.OUTTIME);
                            }
                            _sessionActive = false;
                        } else {
                            var feedbackMessage = chatRequest.feedbackMessage;
                            if (feedbackMessage)
                                $F.formatAndShowNotice(feedbackMessage);
                        }
                        UI.displayNoneForInQueueNotice();
                        pullfailToAgent();
                    }

                }
            }
            var sessions = receivedInfo.sessions;
            if (sessions && sessions.length > 0) {
                var session = sessions[0];
                var processedNotices = [];
                var newMessages = session.newMessages;
                var revokeMessages = {};
                var sessionChangeNotices = session.sessionNotices;
                if (sessionChangeNotices != null && sessionChangeNotices != "" && sessionChangeNotices.length > 0) {
                    for (var sessionChangeNoticeIndex = 0; sessionChangeNoticeIndex < sessionChangeNotices.length; sessionChangeNoticeIndex++) {
                        var notice = sessionChangeNotices[sessionChangeNoticeIndex];
                        processedNotices[processedNotices.length] = notice;
                    }
                }

                if (processedNotices.length > 0) {
                    for (var i = 0; i < processedNotices.length; i++) {
                        var notice = processedNotices[i];
                        if (notice.type === Constants.NoticeMessageType.SUPPLY_INFORMATION) {
                            $F.log('坐席推送通知：' + JSON.stringify(notice));
                            showNoticeForAgent();
                            processedNotices.splice(i, 1);
                        }
                        if (notice.type === Constants.NoticeMessageType.TYPING) {
                            $(".typing-notice").text(i18n.page.typingNotice);
                            if (noticetype) clearTimeout(noticetype);
                            noticetype = setTimeout(function () {
                                $(".typing-notice").text('');
                            }, 3000)
                        }
                        /**
                         "_id":"0-1967-07ed455b-c942-4843-9a9e-38f653cdcb3b",
                         "id":0,
                         "message":"simon 聊天被转接给 DON",
                         "sessionId":1967,
                         "transferToUserName":"DON",
                         "type":11,
                         "userId":"07ed455b-c942-4843-9a9e-38f653cdcb3b"
                         头像没有返回来
                         */
                        else if (notice.type == Constants.NoticeMessageType.TRANSFER_NOTICE) {
                            $(".transfer_notice_start").hide();
                            //获取到转接之后的配置内容
                            var queueConfig = receivedInfo.queueConfig;
                            if (queueConfig) {
                                $config.queue = queueConfig;
                                Constants = init();
                            }
                            if ($config && $config.queue && $config.queue.showTransferNotice) {
                                $F.formatAndShowNotice(notice.message, 0, Constants.formatNoticeType.TRANSFER_NOTICE);
                            }

                            UI.cuestomerService();
                            UI.chatTool();
                            if (notice.extra) {
                                var extra = notice.extra;
                                if (typeof extra == 'string') {
                                    extra = JSON.parse(extra);
                                }
                                for (key in extra) {
                                    if (extra[key]) {
                                        var agent = extra[key];
                                        setAgentInfo(agent);
                                    }
                                }
                            }
                        } else if (notice.type == Constants.NoticeMessageType.INVITE_NOTICE) { //Constants.agent.iconUrls[key] = agentUrl(agent.headImg);
                            $F.formatAndShowNotice(notice.message);
                            UI.cuestomerService();
                            UI.chatTool();
                            if (notice.extra) {
                                var extra = JSON.parse(notice.extra);
                                for (key in extra) {
                                    if (extra[key]) {
                                        var agent = extra[key];
                                        if (agent.headImg) {
                                            Constants.agent.iconUrls[key] = userUrl(agent.id, agent.headImg);
                                        }
                                        setAgentInfo(agent);
                                    }
                                }
                            }
                        } else if (notice.type == Constants.NoticeMessageType.TRANSFER_NOTICE_START) {
                            $F.appendTextToDiv("clientResponseDiv", "<div class=\"no-bg no-yel transfer_notice_start\"><div class=\"notice\">" + notice.message + "</div></div>");
                        } else if (notice.type == Constants.NoticeMessageType.TRANSFER_NOTICE_FAIL) {
                            $(".transfer_notice_start").hide();
                            $F.formatAndShowNotice(notice.message, 0, Constants.formatNoticeType.TRANSFER_NOTICE_START);
                        } else if (notice.type == Constants.NoticeMessageType.AGENT_CLOSE_NOTICE) {
                            $F.formatAndShowNotice(notice.message);
                        } else if (notice.type === Constants.NoticeMessageType.REVOKE_MESSAGE) {
                            //记录这次撤销的消息，可能这条消息还没有append到界面
                            revokeMessages[notice.message] = true;
                            //把界面上已经展示的消息移除
                            $('#clientResponseDiv .lele[data-id=' + notice.message + ']').remove();
                        }
                    }
                }
                //调整顺序 先显示通知然后发送收到的信息
                if (newMessages && newMessages.length > 0) {
                    for (var newMessageIndex = 0; newMessageIndex < newMessages.length; newMessageIndex++) {
                        var newMessage = newMessages[newMessageIndex];
                        var messageId = newMessage.id;
                        if (revokeMessages[messageId]) {
                            //这条消息已经被撤回
                            continue;
                        }
                        var hasThisMessage = messageMap[messageId];
                        if (hasThisMessage) {
                            continue;
                        }
                        var text = newMessage.text;
                        if (text) {
                            if (typeof text === 'string') {
                                text.replaceAll('\r\n', '<br>').replaceAll('\n\r', '<br>').replaceAll('\r', '<br>').replaceAll('\n', '<br>').replaceAll('\b', ' ');
                            }
                            // text = '[MessageFormat data-type="robot" data-key="BOT002"]{"commands":[{"argNames":[],"args":["https://uat.aia.com.cn/robot/imgmsgData/62de483500994627ae97f7ade3af4d0a/articles.xml","1","UTF-8","&lt;![CDATA[&lt;Articles&gt;&lt;item&gt;&lt;Title&gt;&lt;![CDATA[龙腾出行介绍]]&gt;&lt;/Title&gt;&lt;Description&gt;&lt;![CDATA[]]&gt;&lt;/Description&gt;&lt;PicUrl&gt;&lt;![CDATA[https://uat.aia.com.cn/robot/imgmsgData/62de483500994627ae97f7ade3af4d0a/imgmsgItem1.png?t=1525418670697]]&gt;&lt;/PicUrl&gt;&lt;Url&gt;&lt;![CDATA[https://uat.aia.com.cn/robot/imgmsgData/62de483500994627ae97f7ade3af4d0a/index_1.html?t=1525418676026]]&gt;&lt;/Url&gt;&lt;/item&gt;&lt;/Articles&gt;]]&gt;"],"name":"imgtxtmsg","state":1}],"content":"","relatedQuestions":["VIP机场贵宾室","龙腾出行如何使用"],"similarity":1,"type":1}[/MessageFormat]';
                            if (text) {
                                $F.appendTextToDiv("clientResponseDiv", getMessageText(messageId, newMessage.userName, text, newMessage.userId, newMessage.messageType, newMessage.postTime, "", false));
                                setTimeout(blinkTitle(true), 1000);
                            }
                        }
                    }
                }

                if (session.pushRating) {
                    judgeShowRate(Constants.rate.rateType.AGENT_SEND)
                }
                if (session.ifShouldEnd) {
                    UI.displayNoneForInQueueNotice();
                    UI.doEnd();
                    clearShowRatingTimer();
                    var closeType = session.closeType;
                    if (closeType == Constants.CloseType.CLIENT_AFK_CLOSE) {
                        judgeShowRate(Constants.rate.rateType.OUT_TIME);
                    } else {
                        judgeShowRate(Constants.rate.rateType.SHUT_SEND);
                    }
                    $(".pj_cancel, #ratingCloseBtn").css('display', 'none');
                    _sessionActive = false;
                    window.focus();
                }
            }
            //lori added 20100320
            if (receivedInfo.needChange) {
                var newClient = receivedInfo.newClient;
                $config.client.clientId = newClient.id;
            }
        }
    }

    window.endSessionBtnClickHandler = function () {
        if (!endSessionPrint) {
            $F.formatAndShowNotice(i18n.page.chattingOver);
            endSessionPrint = true;
        }
        $config.rateSender = Constants.RateType.SHUT_SEND;
        UI.rateClientShut();
        UI.doEnd();
        if (_sessionActive)
            endSession(Constants.rate.rateType.CLIENT_CLOSE);
    }

    function endSession(closeType) {
        clearShowRatingTimer();
        $config.chatTime = 0;
        $("#time").html("没有活动");
        var closeSessionJSON = {
            actionType: "closeSession",
            senderId: $config.client.clientId,
            senderName: $config.client.clientName,
            sessionId: $config.sessionId,
            closeType: closeType
        };
        $F.doAjaxCall(Constants.ajaxURL, {
            requestType: 'send',
            data: JSON.stringify(closeSessionJSON)
        });
        _sessionActive = false;
        $config.sessionId = -1;
    }

    function showOriginImage(img) {
        if (img) {
            window.open(img.src, "_imgWin", "menubar=no,toolbar=no,titlebar=no,status=no");
        }
    }


    function focusClientMessageBox() {
        if (!_windowInFocus && !_clientMessageBoxInFocus) {
            window.focus();
        }
        $("#clientMessageBox").focus();
    }


    function blinkTitle(flag) {
        return function () {
            if (_titleBlinkTimer) {
                clearTimeout(_titleBlinkTimer);
            }
            if (flag) {
                document.title = "【" + i18n.scripts.newMsg + "】";
            } else {
                document.title = "=" + i18n.scripts.plsCheck + "=";
            }
            flag = !flag;
            if (!_windowInFocus && !_clientMessageBoxInFocus) {
                _titleBlinkTimer = setTimeout(blinkTitle(flag), 1000);
            } else {
                document.title = i18n.page.title;
            }
        }
    }

    function sendAttachment() {
        if ($config.sessionId != -1) {
            if ($F.getBrowserType() == BrowserType.ie) {
                window.open('attachFile.do?action=1', 'sendAttachment', 'left=300, top=150, width=420, height=220, menubar=no, toolbar=no, titlebar=no, directories=no, location=no, scrollbars=no, resizable=yes, status=no');
            } else {
                var form = $('form#chat_upload_form'),
                    input = $("input[type='file']", form);

                input.off('change').on('change', function () {
                    var _fileName = $.trim(input.val());
                    if (!_fileName) {// 提交前的再次检测
                        alert('没有选择上传的文件');
                    } else {
                        var hz = _fileName.substring(_fileName.lastIndexOf(".") + 1);
                        //上传图片格式校验
                        if ($.inArray(hz.toLowerCase, $config.fileAcceptExtensionsArr) > -1) {
                            alert('当前文件格式为：' + hz.toLowerCase + ',文件格式要求：' + $config.fileAcceptExtensionsArr);
                            $(this).val("");
                            return false;
                        }
                        var uploadRet = form.upload({
                            clearForm: true,
                            url: 'uploadh5',
                            upMaxSize: 0,
                            success: function (data) {
                                form[0].reset();
                                if (data.status == 'success') {
                                    var attachURL = data.url;
                                    var content;
                                    var uploadFile = function (file) {
                                        var fName = file.name;
                                        if ($F.isImage(fName)) {
                                            content = '<img src = "' + file.url + '" alt = "' + fName + '" style="max-width: 300px; max-height: 300px;">';
                                        } else {
                                            content = '<a href = "' + file.url + '" target = "_blank" class="attachment">' + fName + '</a>';
                                        }
                                        $F.appendTextToDiv("clientResponseDiv", $F.getDisplayMessage($config.client.clientId, '', content));
                                        sendContent = content.replace(/\\/g, '\\\\').replace(/\"/g, '\\"').replace(/\r\n/g, '').replace(/\n\r/g, '').replace(/\r/g, '').replace(/\n/g, '').replace(/\b/g, '').replace(/\\/g, '\\');
                                        $F.doAjaxCall(Constants.ajaxURL, "requestType=send&data=" + $F.getPostMessageSentInfoJSON(encodeURIComponent(sendContent)));
                                    };
                                    if (data.files) {
                                        $.each(data.files, function (i, file) {
                                            uploadFile(file);
                                        })
                                    } else {
                                        uploadFile(data)
                                    }
                                } else {
                                    alert(i18n.page.uploadFile.fail.format(data.message));
                                }
                            },
                            error: function () {
                                alert(i18n.page.uploadFile.fail.format(""));
                            }
                        });
                        if (uploadRet.code < 0) {
                            alert(i18n.page.uploadFile.fail.format(uploadRet.message));
                        }
                    }
                }).click();
            }
        }
    }

    function callbackOnWindowClose() { //todo: this will be activated by both close window and transfer to another page
        $.ajax({
            url: "jsonHttpRemote.do",
            data: "requestType=closeWindow&sessionId=" + $config.sessionId + "&chatRequestId=" + _chatRequestId,
            async: false
        });
        document.close();
        return;
    }

    onerror = function (msg, url, l) {
        if (_pullTimer) {
            clearTimeout(_pullTimer);
        }
        _pullTimer = setTimeout(pullFromServer, _timeoutForPull);
        $F.log("[clientScript - onerror] msg : " + msg + " url : " + url + "  line : " + l, true);
    }

    function checkForPull() {
        if (_sessionActive) {
            var now = new Date().getTime();
            var elapse = now - _lastPullTime;
            if (elapse > 20 * 1000) {
                $F.log("[clientScript - checkForPull] client no pull for " + elapse + "ms", true);
                if (_pullTimer) {
                    clearTimeout(_pullTimer);
                }
                _pullTimer = setTimeout(pullFromServer, _timeoutForPull);
            }
        }
    }

    /**
     * 发送聊天请求给坐席端
     */
    function createChat(queue) {
        Constants.robot.isRobot = false;
        $config.queueId = queue;
        Constants = init();
        $F.loadingQuestLink();
        if ($config.queue.permFlag == '1') {
            createPrivateChat(queue);
        } else {
            $F.doAjaxCall(Constants.ajaxURL, {
                requestType: "send",
                data: JSON.stringify({
                    actionType: "clientRequest",
                    senderId: $config.client.clientId,
                    senderName: $config.client.clientName,
                    queueId: queue,
                    receiverId: $config.toUserId,
                    from: _from,
                    brand: _brand
                })
            }, processSendReturn);
        }
    }

    //发起机器人转人工的请求
    $F.robotTransferToQueue = function (robotId, queue, transferInfo) {
        $F.doAjaxCall(Constants.ajaxURL, {
            requestType: "send", //agentTransferToQueue {actionType:_transferToQueueRequestTypeString,senderId: _agentId, queueId:lastSelectedQueueId, sessionId:_currentSessionId,comments:commentsField.getValue()
            data: JSON.stringify({
                actionType: 'agentTransferToQueue',
                senderId: robotId,
                queueId: queue,
                comments: transferInfo,
                sessionId: $config.sessionId
            })
        }, function (response) {
            processSendReturn(response, true)
        });
    }


    /**
     * 发送专属聊天请求给坐席端
     */
    function createPrivateChat(queue) {
        Constants.robot.isRobot = false;
        $config.queueId = queue;
        $F.doAjaxCall(Constants.ajaxURL, {
            requestType: "send",
            data: JSON.stringify({
                actionType: 'clientRequest',
                receiverId: $config.toUserId,
                senderId: $config.client.clientId,
                queueId: queue
            })
        }, function (data) {
            if (data.status == 'success') {
                $F.log(JSON.stringify(data));
                if (data.sendResponse) {
                    if (data.sendResponse.sessionId) {
                        acceptByPerm(data.sendResponse);
                        pullFromServer();
                    } else {
                        alert(data.sendResponse.feedbackMessage);
                    }
                } else {
                    alert(i18n.page.permChat.fail.format(JSON.stringify(data)));
                }
            } else {
                alert(i18n.page.permChat.fail.format(JSON.stringify(data)));
            }
        });
    }

    /**
     * 专属队列接通之后初始化数据
     */
    function acceptByPerm(permResponse) {
        if (permResponse.sessionId) {
            UI.loadChatTime($config.queue);
            UI.chatTool();
            $config.sessionId = permResponse.sessionId
            initRateShowInterval();

            var agent = permResponse.usersInSession[0];
            setAgentInfo(agent);
            $("#waitingForAcceptInChatView").html(i18n.page.permChat.accept.format(Constants.agent.name));
            $config.sessionId = permResponse.sessionId;
            $config.thisSessionId = $config.sessionId;
            _startTime = permResponse.pullTime;

            $F.doAjaxCall(Constants.ajaxURL, {
                requestType: 'setCurrentChatSessionId',
                sessionId: $config.sessionId
            });

            chatEditor.readonly(false);
            focusClientMessageBox();

            $("#clientMessageBox").keyup(function () {
                if (_sessionActive) {
                    var msg = $("#clientMessageBox").html();
                    $F.doAjaxCall(Constants.ajaxURL, {
                        requestType: 'send',
                        data: $F.getPostMessageSentInfoJSON(encodeURIComponent($F.encodeStringForHtmlEditor($F.convertEnterToBr(msg))), "postTempMessage")
                    });
                }
            });

            timer = setInterval(function () {
                $config.chatTime++;
                config.common.clientTimeInit++;
                if (parseInt($config.chatTime / 60) > 0) {
                    $("#time").html(parseInt($config.chatTime / 60) + i18n.common.minutes + $config.chatTime % 60 + i18n.common.seconds)
                } else {
                    $("#time").html($config.chatTime % 60 + i18n.common.seconds)
                }
            }, 1000);
            //专属坐席加载完之后加载历史
            _showHistoryChating = true;
            showHistory(function (time, html) {
                if (html) {
                    $F.prependTextToDiv("clientResponseDiv", html);
                }
            }, function (message) {

            })
        } else {
            alert(data.feedbackMessage);
        }
    }

    /**
     *    保存聊天记录
     */
    function saveChat() {
        if ($config.sessionId != -1) {
            var sign = $.md5($config.sessionId + "-" + $config.client.clientId);
            window.open('saveOrPrintChat.do?action=save&sessionId=' + $config.sessionId + "&sign=" + sign, 'saveChat', 'left=300, top=150, width=420, height=420, menubar=no, toolbar=no, titlebar=no, directories=no, location=no, scrollbars=no, resizable=yes, status=no');
        }
    }


    function setAgentInfo(agent) {
        if (agent) {
            var userid = agent.id;
            if ($ROBOT.isRobot(userid)) {
                Constants.robot.name = agent.name;
                Constants.robot.iconUrl = userUrl(userid, agent.headImg);
                Constants.robot.iconAlt = agent.name;
                Constants.robot.robotId = agent.id;
            } else {
                Constants.agent.name = agent.name;
                Constants.agent.iconUrl = userUrl(userid, agent.headImg || "");
                Constants.agent.iconAlt = agent.name;
                Constants.agent.id = agent.id;
            }

        }
    }


    function userUrl(userid, icon) {
        return $COMM.getUserIcon(userid, icon, {
            "clientIcon": Constants.client.iconUrl,
            "robotIcon": Constants.robot.iconUrl,
            "agentIcon": Constants.agent.iconUrls[userid] || Constants.agent.iconUrl,
            "queueId": $config.queueId
        })
    }

    function showClickRate(checkId) {
        $('.reason', "#judge_pj_rg").hide();
        $('#discuss', "#judge_pj_rg").hide();
        $('.reason', "#judge_pj_rg").html("");
        $("#pjwords", "#judge_pj_rg").val("");
        var rating = ratings[parseInt(checkId)];
        if (rating.needComment == 1) {
            $('#discuss', "#judge_pj_rg").show();
        } else {
            $('#discuss', "#judge_pj_rg").hide();
        }

        if (rating.ratingExtends.length > 0 && ratings[parseInt(checkId)].ratingExtendFlag == 1) {
            var ratingExtendText = '<ul class="check-list">';
            if (ratings[parseInt(checkId)].extendTag)
                ratingExtendText += '<li class="que-title que-main-title que-title' + checkId + '">' + ratings[parseInt(checkId)].extendTag + '</li>';
            $.each(rating.ratingExtends, function (j, ratingExtend) {
                if (ratingExtend.type == RateExtendType.CHECKBOX && !ratingExtend.parentId) {
                    ratingExtendText += '<li><label><input class="checkbox-' + ratingExtend.id + '" type="checkbox" name="checkBox' + ratingExtend.id + '" /><i class="ratingExtendkImg ratingExtendImg' + ratingExtend.id + '"></i><span>' + ratingExtend.description + '</span></label><i class="ratingExtendCheckImg ratingExtendCheckImg' + ratingExtend.id + '"></i></li>';
                }
            });
            ratingExtendText += '</ul>';
            $.each(rating.ratingExtends, function (j, ratingExtend) {
                if (!ratingExtend.parentId) {
                    if (ratingExtend.type == RateExtendType.INPUT) {
                        ratingExtendText += '<label class="reason-box reason-box' + ratingExtend.id + '">'
                            + '<span>' + ratingExtend.description + '</span>'
                            + '<input type="text" class="reason-input reason-input' + ratingExtend.id + '" placeholder="' + i18n.page.rate.inputPlaceholder + '" />'
                            + '</label>';
                    } else if (ratingExtend.type == RateExtendType.FOLD) {
                        if (ratingExtend.type == RateExtendType.FOLD && !ratingExtend.parentId) {
                            var filterarray = $.grep(rating.ratingExtends, function (value) {
                                return value.parentId == ratingExtend.id;
                            });
                            ratingExtendText += '<ul class="check-list" data-required="' + ratingExtend.requiredType + '">';
                            ratingExtendText += '<li class="que-title que-title' + checkId + '">' + ratingExtend.description + '</li>';
                            var redioClass = ratingExtend.id + new Date().getTime();
                            $.each(filterarray, function (j, ratingExtend) {
                                if (ratingExtend.type == RateExtendType.CHECKBOX && ratingExtend.parentId) {
                                    ratingExtendText += '<li><label><input class="checkbox-' + ratingExtend.id + '" type="checkbox" name="checkBox' + ratingExtend.id + '" /><i class="ratingExtendkImg ratingExtendImg' + ratingExtend.id + '"></i><span>' + ratingExtend.description + '</span></label><i class="ratingExtendCheckImg ratingExtendCheckImg' + ratingExtend.id + '"></i></li>';
                                } else if (ratingExtend.type == RateExtendType.RADIO) {
                                    var checked = j == 0 ? 'checked = "checked"' : "";
                                    ratingExtendText += '<label class="radio-box radio-box' + ratingExtend.id + '">'
                                        + '<input type="radio" name="' + ratingExtend.parentId + '"  data-sigle="' + redioClass + '"  value="' + ratingExtend.id + '" class="reason-radio reason-radio' + ratingExtend.id + '" ' + checked + ' />'
                                        + '<span>' + ratingExtend.description + '</span>'
                                        + '</label>';
                                }
                            });
                            ratingExtendText += '</ul>';
                            $.each(filterarray, function (j, ratingExtend) {
                                if (ratingExtend.type == RateExtendType.INPUT && ratingExtend.parentId) {
                                    ratingExtendText += '<label class="reason-box reason-box' + ratingExtend.id + '">'
                                        + '<span>' + ratingExtend.description + '：</span>'
                                        + '<input type="text" class="reason-input reason-input' + ratingExtend.id + '" placeholder="' + i18n.page.rate.inputPlaceholder + '" />'
                                        + '</label>';
                                } else if (ratingExtend.type == RateExtendType.STAR) {
                                    ratingExtendText += '<label class="reason-box reason-box' + ratingExtend.id + '">'
                                        + '<span>' + ratingExtend.description + '</span>';
                                    if (ratingExtend.rateStars) {
                                        var rateStars = ratingExtend.rateStars;
                                        if (rateStars.length > 0) {
                                            ratingExtendText += '<span class="star-list-head hide">' + rateStars[0].ratingDescription + '</span>';
                                            ratingExtendText += '<ul class="star-list">';
                                            $.each(rateStars, function (m, rateStar) {
                                                var active = '';
                                                if (rateStar && rateStar.active) {
                                                    active = 'active';
                                                }
                                                ratingExtendText += '<li data-descclass="star-description-' + ratingExtend.id + '" data-starclass="star-description-li' + rateStar.ratingId + '" class="' + active + ' star-li star-' + ratingExtend.id + ' star-id-' + rateStar.ratingId + ' star-weight-' + rateStar.ratingWeight + '" data-need="' + rateStar.needComment + '" data-textarea=".suggest-textarea' + ratingExtend.id + '" data-description="' + rateStar.ratingDescription + '" data-weight="' + rateStar.ratingWeight + '"></li>';
                                            });
                                            ratingExtendText += '<span class="star-list-tail hide">' + rateStars[rateStars.length - 1].ratingDescription + '</span>';
                                            ratingExtendText += '<span class="star-description star-description-' + ratingExtend.id + ' hide"></span></ul>';
                                        }
                                    }
                                    ratingExtendText += '<div class="suggest_textarea suggest-textarea' + ratingExtend.id + '" style="display: none ">' +
                                        '<div class="text"><textarea name="pjwords" placeholder="请输入" maxlength="' + i18n.page.maxWrite + '"></textarea>' +
                                        '<div class="words" id="words2" num="' + i18n.page.maxWrite + '">' + i18n.page.wordsCountHint + '</div></div></div>';
                                    ratingExtendText += '</label>';
                                }
                            });
                        }
                    } else if (ratingExtend.type == RateExtendType.STAR) {
                        ratingExtendText += '<label class="reason-box reason-box' + ratingExtend.id + '">'
                            + '<span>' + ratingExtend.description + '</span>';
                        if (ratingExtend.rateStars) {
                            var rateStars = ratingExtend.rateStars;
                            if (rateStars.length > 0) {
                                ratingExtendText += '<span class="star-list-head hide">' + rateStars[0].ratingDescription + '</span>';
                                ratingExtendText += '<ul class="star-list">';
                                $.each(rateStars, function (m, rateStar) {
                                    ratingExtendText += '<li data-descclass="star-description-' + ratingExtend.id + '" data-starclass="star-description-li-' + rateStar.ratingId + '" class="star-li star-' + ratingExtend.id + ' star-id-' + rateStar.ratingId + ' star-weight-' + rateStar.ratingWeight + '" data-need="' + rateStar.needComment + '" data-description="' + rateStar.ratingDescription + '" data-textarea=".suggest-textarea' + ratingExtend.id + '" data-weight="' + rateStar.ratingWeight + '"></li>';
                                });
                                ratingExtendText += '<span class="star-list-tail hide">' + rateStars[rateStars.length - 1].ratingDescription + '</span>';
                                ratingExtendText += '<span class="star-description star-description-' + ratingExtend.id + ' hide"></span></ul>';
                            }
                            ratingExtendText += '<div class="suggest_textarea suggest-textarea' + ratingExtend.id + ' hide">' + $("#discuss").html() + '</div>';
                        }
                        ratingExtendText += '</label>';
                    }
                }
            });
            $('.reason',"#judge_pj_rg").html(ratingExtendText);
            $(".star-li","#judge_pj_rg").off().on("click", function () {
                $(this).addClass("active select");
                $(this).prevAll("li").addClass('active');
                $(this).prevAll("li").removeClass('select');
                $(this).nextAll("li").removeClass('active select');
                var descClass = $(this).data("descclass"), starclass = $(this).data("starclass"), needConmment = $(this).data("need")
                    , textarea = $(this).data("textarea"), desc = $(this).data("description");
                if (desc) {
                    $("." + descClass, "#judge_pj_rg").removeClass(function (index, className) {
                        var removeClassName = "";
                        $.each(className.split(" "), function (i, name) {
                            if (name.indexOf("star-description-li") > -1) {
                                removeClassName = name;
                            }
                        })
                        return removeClassName;
                    });
                    $("." + descClass, "#judge_pj_rg").text(desc);
                    $("." + descClass, "#judge_pj_rg").css("display", "");
                    $("." + descClass, "#judge_pj_rg").addClass(starclass);
                }
                if (needConmment === 0) {
                    $(textarea).css("display", "none");
                } else {
                    $(textarea).css("display", "block");
                }
            });
            $('.reason', "#judge_pj_rg").show();
        }
        $(".rate-title", "#judge_pj_rg").html(i18n.common.rateTitle);
        $('#pjwords', "#judge_pj_rg").attr('placeholder', i18n.page.rate.inputPlaceholder);
        $('textarea[name="pjwords"]', "#judge_pj_rg").attr('placeholder', i18n.page.rate.inputPlaceholder);
        $(".rate-tip", "#judge_pj_rg").html(i18n.common.rateBody);
        $("h3", "#judge_pj_rg").html(i18n.common.rateCommentTitle);
        $(".advice", "#judge_pj_rg").html(i18n.common.rateCommentBody);
        $("#ratingCancel", "#judge_pj_rg").html(i18n.common.rateCancel);
        $("#ratingSubmit", "#judge_pj_rg").html(i18n.common.rateSubmit);
        $("#discuss h4", "#judge_pj_rg").text(i18n.common.rateTitle);
        $("#ratingSubmitAfter").html(i18n.common.rateClose);
        $(".rate .content h2").html(i18n.common.rateThanksHead);
        $(".rate .content p").html(i18n.common.rateThanksBody);
    }

    function updateRateTimes(rateTtpe) {
        Constants.rate.rateSender = rateTtpe;
        if ((Constants.rate.maxAllowRateTimes < 0) || (Constants.rate.maxAllowRateTimes > 0 && Constants.rate.maxAllowRateTimes > Constants.rate.hasRateTimes)) {
            Constants.rate.hasRateTimes++;
            $F.log("全部推送次数" + Constants.rate.hasRateTimes);
            if (rateTtpe == Constants.rate.rateType.CLIENT_CLOSE) {
                if (!Constants.rate.client.hasRate) {
                    if ((Constants.rate.client.allowRateTimes < 0) || (Constants.rate.client.allowRateTimes > 0 && Constants.rate.client.allowRateTimes > Constants.rate.client.hasRateTimes)) {
                        if (Constants.rate.client.allowRateWhenEnd) {
                            Constants.rate.client.hasRateTimes++;
                            $F.log("客户关闭聊天满意度推送次数" + Constants.rate.client.hasRateTimes);
                        }
                    }
                }
            } else if (rateTtpe == Constants.rate.rateType.CLIENT_SEND) {
                if ((Constants.rate.client.allowRateTimes < 0) || (Constants.rate.client.allowRateTimes > 0 && Constants.rate.client.allowRateTimes > Constants.rate.client.hasRateTimes)) {
                    Constants.rate.client.hasRateTimes++;
                    $F.log("客户满意度推送次数" + Constants.rate.client.hasRateTimes);
                    Constants.rate.client.hasRate = true;
                }
            } else if (rateTtpe == Constants.rate.rateType.AGENT_SEND) {
                if ((Constants.rate.agent.allowRateTimes < 0) || (Constants.rate.agent.allowRateTimes > 0 && Constants.rate.agent.allowRateTimes > Constants.rate.agent.hasRateTimes)) {
                    Constants.rate.agent.hasRateTimes++;
                    $F.log("坐席满意度推送次数" + Constants.rate.agent.hasRateTimes);
                    if (!Constants.rate.agent.allowRateWhenEnd) {
                        Constants.rate.agent.hasRate = true;
                    }
                }
            } else if (rateTtpe == Constants.rate.rateType.OUT_TIME) {
                if ((Constants.rate.agent.allowRateTimes < 0) || (Constants.rate.agent.allowRateTimes > 0 && Constants.rate.agent.allowRateTimes > Constants.rate.agent.hasRateTimes)) {
                    Constants.rate.agent.hasRateTimes++;
                    $F.log("坐席满意度推送次数" + Constants.rate.agent.hasRateTimes);
                    if (!Constants.rate.agent.allowRateWhenEnd) {
                        Constants.rate.agent.hasRate = true;
                    }
                } else {
                    clearShowRatingTimer();
                }
            } else if (rateTtpe == Constants.rate.rateType.SHUT_SEND) {
                if (!Constants.rate.agent.hasRate) {
                    if ((Constants.rate.agent.allowRateTimes < 0) || (Constants.rate.agent.allowRateTimes > 0 && Constants.rate.agent.allowRateTimes > Constants.rate.agent.hasRateTimes)) {
                        Constants.rate.agent.hasRateTimes++;
                        $F.log("坐席关闭聊天满意度推送次数" + Constants.rate.agent.hasRateTimes);
                    }
                } else {
                    $F.log("坐席已经推送过满意度");
                }
            } else if (rateTtpe == Constants.rate.rateType.INTERVAL_SEND) {
                if ((Constants.rate.agent.allowRateTimes < 0) || (Constants.rate.agent.allowRateTimes > 0 && Constants.rate.agent.allowRateTimes > Constants.rate.agent.hasRateTimes)) {
                    $F.log("自动满意度推送次数" + Constants.rate.hasRateTimes);
                    Constants.rate.hasRateTimes++;
                }
            }
        } else {
            $F.log("超出了最大的推送满意度次数");
        }
    }

    window.judgeShowRate = function (rateTtpe) {
        Constants.rate.rateSender = rateTtpe;
        if ((Constants.rate.maxAllowRateTimes < 0) || (Constants.rate.maxAllowRateTimes > 0 && Constants.rate.maxAllowRateTimes > Constants.rate.hasRateTimes)) {
            if (rateTtpe == Constants.rate.rateType.CLIENT_CLOSE) {
                if (Constants.rate.client.rateOrEnd == Constants.rate.openRate.NOT_SHOW_RATE) {
                    clearShowRatingTimer();
                    endSessionBtnClickHandler();
                } else {
                    if (Constants.rate.client.allowRateWhenEnd && !Constants.rate.client.hasRate) {
                        if ((Constants.rate.client.allowRateTimes < 0) || (Constants.rate.client.allowRateTimes > 0 && Constants.rate.client.allowRateTimes > Constants.rate.client.hasRateTimes)) {
                            UI.rateClientShut();
                            showRating()
                        }
                    } else {
                        clearShowRatingTimer();
                        endSessionBtnClickHandler();
                    }
                }
                $('.confirm-container').hide();
            } else if (rateTtpe == Constants.rate.rateType.CLIENT_SEND) {
                if ((Constants.rate.client.allowRateTimes < 0) || (Constants.rate.client.allowRateTimes > 0 && Constants.rate.client.allowRateTimes > Constants.rate.client.hasRateTimes)) {
                    UI.rateClientSend();
                    showRating();
                }
            } else if (rateTtpe == Constants.rate.rateType.AGENT_SEND) {
                if ((Constants.rate.agent.allowRateTimes < 0) || (Constants.rate.agent.allowRateTimes > 0 && Constants.rate.agent.allowRateTimes > Constants.rate.agent.hasRateTimes)) {
                    UI.rateAgentSend();
                    showRating();
                }
            } else if (rateTtpe == Constants.rate.rateType.OUT_TIME) {
                if (Constants.rate.agent.allowRateWhenEnd) {
                    if ((Constants.rate.agent.allowRateTimes < 0) || (Constants.rate.agent.allowRateTimes > 0 && Constants.rate.agent.allowRateTimes > Constants.rate.agent.hasRateTimes)) {
                        UI.rateOutTime();
                        showRating();
                    }
                }
            } else if (rateTtpe == Constants.rate.rateType.SHUT_SEND) {
                if (Constants.rate.agent.allowRateWhenEnd) {
                    if (!Constants.rate.agent.hasRate) {
                        if ((Constants.rate.agent.allowRateTimes < 0) || (Constants.rate.agent.allowRateTimes > 0 && Constants.rate.agent.allowRateTimes > Constants.rate.agent.hasRateTimes)) {
                            UI.rateAgentShut();
                            showRating();
                            // $F.appendTextToDiv("clientResponseDiv", $F.formatNotice("坐席已经关闭与您的聊天。"));
                        }
                    } else {
                        $F.log("坐席已经推送过满意度");
                    }
                }
            } else if (rateTtpe == Constants.rate.rateType.INTERVAL_SEND) {
                $config.rateSender = Constants.RateType.INTERVAL_SEND;
                if ((Constants.rate.agent.allowRateTimes < 0) || (Constants.rate.agent.allowRateTimes > 0 && Constants.rate.agent.allowRateTimes > Constants.rate.agent.hasRateTimes)) {
                    $(".pj_cancel, #ratingCloseBtn").css('display', 'none');
                    UI.rateAgentSend();
                    showRating();
                } else {
                    clearShowRatingTimer();
                }
            }
        } else {
            $F.log("超出了最大的推送满意度次数");
            $(".bg_cover ").hide()
            if (rateTtpe == Constants.rate.rateType.CLIENT_CLOSE) {
                if (Constants.rate.client.rateOrEnd != Constants.rate.openRate.NOT_SHOW_RATE) {
                    $F.rateAfter();
                }
            }
        }
    }

    window.loginWhenVisit = function (callback) {
        $('.bg_cover').hide();
        //如果机器人是中兴的机器人就需要去执行登陆的功能
        var rec = $config.queue.robotEngineConfig;
        var recp = rec.property;
        if (rec && recp.loginUrl) {
            var queue = 0;
            if (recp.queue) {
                queue = recp.queue;
            } else {
                queue = $config.queueId;
            }
            var clientType = $config.client.clientType;
            if (clientType == Constants.CLIENTTYPE.VISITOR) { //判断是不是访客, 访客模式就去校验
                //1 获取cookie
                var cookies = document.cookie;
                if (cookies.length > 0) {
                    var cookieArr = cookies.split(";");
                    // var UCSSSOLanguage = "en_US", UCSLoginName = "sher", UCSSSOAccount = "A0373772289949523968",
                    //     UCSSSOUser = "U0373772289949523968", UCSSSOToken = "59959bc093AB4BbEA6f3508c79CCA3D42C77843eFcB043869c7B3A2980a86172",
                    //     loginType = "channel";
                    var UCSSSOLanguage = "", UCSLoginName = "", UCSSSOAccount = "",
                        UCSSSOUser = "", UCSSSOToken = "",
                        loginType = "";
                    $.each(cookieArr, function (i, cookie) {
                        var param = cookie.trim().split('=');
                        if (param[0] == 'UCSSSOLanguage') {
                            UCSSSOLanguage = param[1];
                        } else if (param[0] == 'UCSLoginName') {
                            UCSLoginName = param[1];
                        } else if (param[0] == 'UCSSSOAccount') {
                            UCSSSOAccount = param[1];
                        } else if (param[0] == 'UCSSSOUser') {
                            UCSSSOUser = param[1];
                        } else if (param[0] == 'UCSSSOToken') {
                            UCSSSOToken = param[1];
                        } else if (param[0] == 'loginType') {
                            loginType = param[1];
                        }
                    });
                    //判断token 如果没有就去认证
                    if (UCSSSOToken !== '') {
                        checkRoleManager(UCSSSOAccount, function () {
                            $.ajax({
                                type: "POST",
                                url: "interfacezte.do",
                                contentType: "application/json", //必须有
                                dataType: "json", //表示返回值类型，不必须
                                data: JSON.stringify({
                                    userId: UCSSSOUser,
                                    accountId: UCSSSOAccount,
                                    token: UCSSSOToken,
                                    lang: UCSSSOLanguage,
                                    queue: $config.queueId
                                }),  //相当于 data: "{'username':'admin', 'password':'123456'}",
                                success: function (data) {
                                    $ROBOT.transferDialog("", function () {
                                        if (data.code.code == '0000') {
                                            $F.log("verify data" + JSON.stringify(data));
                                            //成功了之后就直接
                                            removeWindowBind('code is 0000');
                                            location.href = recp.wechatUrl + "?queue=" + queue + "&from=" + _from + "&sessionId=" + $config.sessionId + "&transfer=true&loginName=" + UCSSSOUser + "&password=" + UCSSSOAccount;
                                        } else {
                                            removeWindowBind('code not 0000');
                                            location.href = recp.loginUrl + '?source=' + recp.source + "&backurl=" + encodeURIComponent(recp.wechatUrl + "?from=" + _from + "&sessionId=" + $config.sessionId + "&transfer=true&queue=" + queue) + "&lang=" + UCSSSOLanguage;
                                        }
                                    })
                                }
                            });
                        })
                    } else {
                        $ROBOT.transferDialog("", function () {
                            removeWindowBind('UCSSSOToken is null ');
                            location.href = recp.loginUrl + '?source=' + recp.source + "&backurl=" + encodeURIComponent(recp.wechatUrl + "?from=" + _from + "&sessionId=" + $config.sessionId + "&transfer=true&queue=" + queue) + "&lang=" + UCSSSOLanguage;
                        })
                    }
                } else {
                    $ROBOT.transferDialog("", function () {
                        removeWindowBind('UCSSSOToken is null ');
                        location.href = recp.loginUrl + '?source=' + recp.source + "&backurl=" + encodeURIComponent(recp.wechatUrl + "?from=" + _from + "&sessionId=" + $config.sessionId + "&transfer=true&queue=" + queue) + "&lang=" + UCSSSOLanguage;
                    })
                }
            }
        } else {
            callback();
        }
    }

    function checkRoleManager(UCSSSOAccount, callBack) {
        $.ajax({
            type: "POST",
            url: "rolemanager.do",
            contentType: "application/json", //必须有
            dataType: "json", //表示返回值类型，不必须
            data: JSON.stringify({
                accountId: UCSSSOAccount,
                queue: $config.queueId
            }),  //相当于 //data: "{'username':'admin', 'password':'123456'}",
            success: function (data) {
                var rec = $config.queue.robotEngineConfig;
                var recp = rec.property;
                if (data && data.code && data.code.code && data.code.code == '0000') {
                    $F.log("Role Manager Data" + JSON.stringify(data));
                    if (data.bo && data.bo.vipFlag && data.bo.vipFlag == 'Y') {
                        //成功了之后就直接
                        if ($.isFunction(callBack)) {
                            callBack();
                        }
                    } else {
                        if (recp.roleManagerTips) {
                            $F.formatAndShowNotice(recp.roleManagerTips);
                        }
                    }
                } else {
                    //权限不够需要提示给客户
                    if (recp.roleManagerTips) {
                        $F.formatAndShowNotice(recp.roleManagerTips);
                    }
                }
            }
        });
    }

    /**
     * 聊天历史
     */
    function showHistory(callBack, callbackNoHistory) {
        var showHisChating = config.mobile.showHisChating;
        if (_showHistoryChating) {
            if ($config.queue.historyLoad != -1) {
                $.ajax({
                    url: Constants.ajaxURL,
                    method: 'POST',
                    data: {
                        requestType: 'getHistorySessionMessagesForUser',
                        clientId: $config.client.clientId,
                        fromMessageId: _fromMessageId,
                        perm: $config.queue.permFlag,
                        sessionId: $config.sessionId,
                        startTime: _startTime,
                        maxCount: showHisChating || 10
                    },
                    success: function (response) {
                        if (response.status == 'success') {
                            if (response.messages && response.messages.length > 0) {
                                $(".button-load-talk").show();
                                if (showHistoryMsgTip) {
                                    $F.formatNotice('<div class="no-bg no-yel"><div class="notice">' + i18n.page.history + '</div></div>', true);
                                    showHistoryMsgTip = false;
                                }
                                var postTime = 0;
                                var html = '';
                                var messages = response.messages;
                                $.each(messages, function (i, msg) {
                                    if (msg.revokeFlag != 1) {
                                        if (i == 0) {
                                            postTime = msg.postTime;
                                        }
                                        _fromMessageId = msg.id;
                                        html = getMessageText(msg.id, msg.userName, msg.text, msg.userId, msg.messageType, msg.postTime, msg.icon, true) + html;
                                    }
                                })
                                if ($.isFunction(callBack))
                                    callBack($F.getLocalTime(postTime), html);
                                $("#clientResponseDiv").scrollTop(0);
                            } else {
                                if ($.isFunction(callbackNoHistory))
                                    callbackNoHistory("NOHIS");
                            }
                        } else {
                            $("#clientResponseDiv").scrollTop($("#clientResponseDiv")[0].scrollHeight);
                            $F.formatAndShowNotice(i18n.page.noHistory);
                            if ($.isFunction(callbackNoHistory))
                                callbackNoHistory("ERROR");
                        }
                    }
                });
            }
        }
    }
})(window);
